﻿///**
//* Cookie plugin
//*
//* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
//* Dual licensed under the MIT and GPL licenses:
//* http://www.opensource.org/licenses/mit-license.php
//* http://www.gnu.org/licenses/gpl.html
//*
//*/

//jQuery.cookie = function (b, j, m) { if (typeof j != "undefined") { m = m || {}; if (j === null) { j = ""; m.expires = -1 } var e = ""; if (m.expires && (typeof m.expires == "number" || m.expires.toUTCString)) { var f; if (typeof m.expires == "number") { f = new Date(); f.setTime(f.getTime() + (m.expires * 24 * 60 * 60 * 1000)) } else { f = m.expires } e = "; expires=" + f.toUTCString() } var l = m.path ? "; path=" + (m.path) : ""; var g = m.domain ? "; domain=" + (m.domain) : ""; var a = m.secure ? "; secure" : ""; document.cookie = [b, "=", encodeURIComponent(j), e, l, g, a].join("") } else { var d = null; if (document.cookie && document.cookie != "") { var k = document.cookie.split(";"); for (var h = 0; h < k.length; h++) { var c = jQuery.trim(k[h]); if (c.substring(0, b.length + 1) == (b + "=")) { d = decodeURIComponent(c.substring(b.length + 1)); break } } } return d } };
jQuery.loadScript = function (url, options) {
    options = $.extend(options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });
    return jQuery.ajax(options);
};
jQuery.loadCss = function (url) {
    var cssNode = document.createElement('link');
    cssNode.rel = 'stylesheet';
    cssNode.type = 'text/css';
    cssNode.media = 'screen';
    cssNode.href = url;
    var head = document.head || document.getElementsByTagName("head")[0];
    head.appendChild(cssNode);
};
jQuery.loadHtml = function (url, options) {
    options = $.extend(options || {}, {
        dataType: "html",
        cache: true,
        url: url
    });
    return jQuery.ajax(options);
};
var K;
jQuery.ploadFile = function (sfTp, fnCallBack) {
    function seteditoropt() {
        K = KindEditor;
//        K.DEBUG = true;
        K.basePath = K.options.basePath = '/jqPlugin/kindeditor/';
        K.options.themesPath = K.options.basePath + 'themes/';
        K.options.langPath = K.options.basePath + 'lang/';
        K.options.pluginsPath = K.options.basePath + 'plugins/';
        typeof (fnCallBack) == "function" && fnCallBack();
    };
    if (sfTp == "Tip") {
        jQuery.loadScript("/jqPlugin/poshytip/jquery.poshytip.min.js").done(fnCallBack);
        jQuery.loadCss("/jqPlugin/poshytip/tip-yellowsimple/tip-yellowsimple.css");
        jQuery.loadCss("/jqPlugin/poshytip/tip-yellowsimple/tip-yellow.css");
    }
    else if (sfTp == "Grid") {
        jQuery.loadScript("/??jqPlugin/sigma_grid/gt_grid_all.js,jqPlugin/sigma_grid/gtBaseJs.js?t=" + new Date().getTime()).done(fnCallBack);
        jQuery.loadCss("/jqPlugin/sigma_grid/gt_grid.css");
    }
    else if (sfTp == "Bought") {
        jQuery.loadScript("/themes/Style1/jsBought.js" + '?t=' + new Date().getTime()).done(fnCallBack);
    }
    else if (sfTp == "layer") {
        typeof (layer) != 'undefined' && fnCallBack() || jQuery.loadScript("/jqPlugin/layer/layer.min.js").done(fnCallBack);
    }
    else if (sfTp == "laytpl") {
        typeof (laytpl) != 'undefined' && fnCallBack() || jQuery.loadScript("/jqPlugin/js/laytpl.js").done(fnCallBack);
    }
    else if (sfTp == "uploadify") {
        typeof (swfobject) != 'undefined' && fnCallBack() || jQuery.loadScript("/jqPlugin/uploadify/jquery.uploadify.min.js").done(fnCallBack);
        jQuery.loadCss("/jqPlugin/uploadify/uploadify.css");
    }
    else if (sfTp == "kindeditor") {
        typeof (swfobject) != 'undefined' && fnCallBack() || jQuery.loadScript("/??jqPlugin/kindeditor/kindeditor.js,jqPlugin/kindeditor/lang/zh_CN.js").done(seteditoropt);
        jQuery.loadCss("/jqPlugin/kindeditor/themes/default/default.css");
    }
};
jQuery.getValidateImg = function (cimgid) {
    $("#" + cimgid).html('').append($('<img  align="top" src="/pgajax.axd?VDC=1&PRAD=' + sCurrRadom + '&t=' + new Date().getTime() + '"  />').click(function () { jQuery.getValidateImg(cimgid); }));
};
jQuery.ValidateImgCode = function (inpcode, fnCallBack) {
    jQuery.loadHtml('/pgajax.axd?VDC=2&INPVDCD=' + inpcode + '&PRAD=' + sCurrRadom + '&t=' + new Date().getTime()).done(fnCallBack);
};
jQuery.setLoginOut = function () {
    jQuery.loadHtml('/pgajax.axd?LOGINOUT=1').done(function () { window.location.reload(true); });
};
var _uploadbtn = [];
jQuery.setUploadFile = function (_dombtnId, _extPara, fnCallBack) {
    if (!_dombtnId) { return; }
    var _dombtn = ($("#" + _dombtnId).length > 0 ? $("#" + _dombtnId)[0] : $("<input type='button' style='display:none;' id='" + _dombtnId + "' value='' />").appendTo("body")[0]);
    if (_uploadbtn[_dombtnId]) { _uploadbtn[_dombtnId].remove(); _uploadbtn[_dombtnId] = null; }
    _uploadbtn[_dombtnId] = K.uploadbutton({
        button: _dombtn,
        url: '/pgajax.axd?F_UPLOAD=1',
        extraParams: _extPara || { fType: '', FileId: '', RelId: '', rType1: '0', rType2: '', blSave: '0' },
        afterUpload: function (data) {
            fnCallBack(data);
        },
        afterError: function (str) {
            alert('自定义错误信息: ' + str);
        }
    });
    _uploadbtn[_dombtnId].fileBox.change(function (e) {
        _uploadbtn[_dombtnId].submit();
    });
    //    $(_uploadbtn.fileBox).trigger("click");
};

 (function(window, undefined){
 //如果已经支持了，则不再处理
 if( window.localStorage )
     return;
 /*
  * IE系列
  */
 var userData = {
     //存储文件名（单文件小于128k，足够普通情况下使用了）
     file : window.location.hostname || "localStorage",
     //key'cache
     keyCache : "localStorageKeyCache",
     //keySplit
     keySplit : ",",
     // 定义userdata对象
     o : null,
     //初始化
     init : function(){
         if(!this.o){
             try{
                 var box = document.body || document.getElementsByTagName("head")[0] || document.documentElement, o = document.createElement('input');
                 o.type = "hidden";
                 o.addBehavior ("#default#userData");
                 box.appendChild(o);
                 //设置过期时间
                 var d = new Date();
                 d.setDate(d.getDate()+365);
                 o.expires = d.toUTCString();
                 //保存操作对象
                 this.o = o;
                 //同步length属性
                 window.localStorage.length = this.cacheKey(0,4);
             }catch(e){
                 return false;
             }
         };
         return true;
     },
     //缓存key，不区分大小写（与标准不同）
     //action  1插入key 2删除key 3取key数组 4取key数组长度
     cacheKey : function( key, action ){
         if( !this.init() )return;
         var o = this.o;
         //加载keyCache
         o.load(this.keyCache);
         var str = o.getAttribute("keys") || "",
             list = str ? str.split(this.keySplit) : [],
             n = list.length, i=0, isExist = false;
         //处理要求
         if( action === 3 )
             return list;
         if( action === 4 )
             return n;
         //将key转化为小写进行查找和存储
         key = key.toLowerCase();
         for(; i<n; i++){
             if( list[i] === key ){
                 isExist = true;
                 if( action === 2 ){
                     list.splice(i,1);
                     n--; i--;
                 }
             }
         }
         if( action === 1 && !isExist )
             list.push(key);
         //存储
         o.setAttribute("keys", list.join(this.keySplit));
         o.save(this.keyCache);
     },
 //核心读写函数
     item : function(key, value){
         if( this.init() ){
             var o = this.o;
             if(value !== undefined){ //写或者删
                 //保存key以便遍历和清除
                 this.cacheKey(key, value === null ? 2 : 1);
                 //load
                 o.load(this.file);
                 //保存数据
                 value === null ? o.removeAttribute(key) : o.setAttribute(key, value+"");
                 // 存储
                 o.save(this.file);
             }else{ //读
                 o.load(this.file);
                 return o.getAttribute(key) || null;
             }
             return value;
         }else{
             return null;
         }
         return value;
     },
     clear : function(){
         if( this.init() ){
             var list = this.cacheKey(0,3), n = list.length, i=0;
             for(; i<n; i++)
                 this.item(list[i], null);
         }
     }
 };
 //扩展window对象，模拟原生localStorage输入输出
 window.localStorage = {
     setItem : function(key, value){userData.item(key, value); this.length = userData.cacheKey(0,4)},
     getItem : function(key){return userData.item(key)},
     removeItem : function(key){userData.item(key, null); this.length = userData.cacheKey(0,4)},
     clear : function(){userData.clear(); this.length = userData.cacheKey(0,4)},
     length : 0,
     key : function(i){return userData.cacheKey(0,3)[i];},
     isVirtualObject : true
 };
 })(window);

(function (window, localStorage, undefined) {
    var LS = {
        set: function (key, value) {
            //在iPhone/iPad上有时设置setItem()时会出现诡异的QUOTA_EXCEEDED_ERR错误
            //这时一般在setItem之前，先removeItem()就ok了
            if (this.get(key) !== null)
                this.remove(key);
            localStorage.setItem(key, value);
        },
        //查询不存在的key时，有的浏览器返回undefined，这里统一返回null
        get: function (key) {
            var v = localStorage.getItem(key);
            return v === undefined ? null : v;
        },
        remove: function (key) { localStorage.removeItem(key); },
        clear: function () { localStorage.clear(); },
        each: function (fn) {
            var n = localStorage.length, i = 0, fn = fn || function () { }, key;
            for (; i < n; i++) {
                key = localStorage.key(i);
                if (fn.call(this, key, this.get(key)) === false)
                    break;
                //如果内容被删除，则总长度和索引都同步减少
                if (localStorage.length < n) {
                    n--;
                    i--;
                }
            }
        }
    },
 j = window.jQuery, c = window.Core;
    //扩展到相应的对象上
    window.LS = window.LS || LS;
    //扩展到其他主要对象上
    if (j) j.LS = j.LS || LS;
    if (c) c.LS = c.LS || LS;
})(window, window.localStorage);

var HtmlUtil = {
    /*3.用正则表达式实现html转码*/
    htmlEncode: function (str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        return s;
    },
    /*4.用正则表达式实现html解码*/
    htmlDecode: function (str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        return s;
    }
};
//显示系统通知
function MsgShow(objmsg) {
    setTimeout(function () { MsgShow(objmsg) }, 8000);
    var dtMsgDt = LS.get('FwsSysMsgGetDt');
    if (dtMsgDt == null || parseInt(((new Date()) - Date.parse(dtMsgDt)) / 1000) > 30) {
        $.ajax({
            type: "POST",
            url: shUrlBase + "pgajax.axd", //shUrlBase + "UserControl/SetClientInfo.aspx",
            processData: true,
            data: { SYS_MSG_COUNT: '1' },
            success: function (data, textStatus) {
                doMsgShowEm(data);
                LS.set('FwsSysMsgGetDt', new Date());
                LS.set('FwsSysMsgCount', data);
            }
        });
    } else {
        var iMsgCount = LS.get('FwsSysMsgCount');
        doMsgShowEm(iMsgCount);
    }
    function doMsgShowEm(iMsgCount) {
        if (iMsgCount == '' || iMsgCount == '0') { objmsg.innerHTML = "<img src=\"" + shUrlBase + "Images/desktop/Png16/2008113016513258.gif\" align=\"top\" style=\"margin-top: 2px; width:16px;height:16px;\" />消息通知(0)"; } else { objmsg.innerHTML = "<img src=\"" + shUrlBase + "Images/desktop/Png16/2008113016511784.gif\" align=\"top\" style=\"margin-top: 2px;width:16px;height:16px;\" />消息通知(<font style='color:red;'>" + iMsgCount + "</font>)"; }
    };
};
//显示待办事务
function FlowActShow(objmsg) {
    setTimeout(function () { FlowActShow(objmsg) }, 18000);
    var dtMsgDt = LS.get('FwsFlowActGetDt');
    if (dtMsgDt == null || parseInt(((new Date()) - Date.parse(dtMsgDt)) / 1000) > 30) {
        $.ajax({
            type: "POST",
            url: shUrlBase + "pgajax.axd", //shUrlBase + "UserControl/SetClientInfo.aspx",
            processData: true,
            data: { FLOW_ACT_COUNT: '1' },
            success: function (data, textStatus) {
                doFlowActShowEm(data);
                LS.set('FwsFlowActGetDt', new Date());
                LS.set('FwsFlowActCount', data);
            }
        });
    } else {
        var iMsgCount = LS.get('FwsFlowActCount');
        doFlowActShowEm(iMsgCount);
    }
    function doFlowActShowEm(iMsgCount) {
        if (iMsgCount == '' || iMsgCount == '0') { objmsg.innerHTML = "<img src=\"" + shUrlBase + "Images/desktop/Png16/foward.png\" align=\"top\" style=\"margin-top: 2px;\" />待办事务(0)"; } else { objmsg.innerHTML = "<img src=\"" + shUrlBase + "Images/desktop/Png16/2008113016521865.gif\" align=\"top\" style=\"margin-top: 2px;\" />待办事务(<font style='color:red;'>" + iMsgCount + "</font>)"; }
    };
};

//(function($) {

//    /** jGrowl Wrapper - Establish a base jGrowl Container for compatibility with older releases. **/
//    $.jGrowl = function(m, o) {
//        // To maintain compatibility with older version that only supported one instance we'll create the base container.
//        if ($('#jGrowl').size() == 0)
//            $('<div id="jGrowl"></div>').addClass((o && o.position) ? o.position : $.jGrowl.defaults.position).appendTo('body');

//        // Create a notification on the container.
//        $('#jGrowl').jGrowl(m, o);
//    };


//    /** Raise jGrowl Notification on a jGrowl Container **/
//    $.fn.jGrowl = function(m, o) {
//        if ($.isFunction(this.each)) {
//            var args = arguments;

//            return this.each(function() {
//                var self = this;

//                /** Create a jGrowl Instance on the Container if it does not exist **/
//                if ($(this).data('jGrowl.instance') == undefined) {
//                    $(this).data('jGrowl.instance', $.extend(new $.fn.jGrowl(), { notifications: [], element: null, interval: null }));
//                    $(this).data('jGrowl.instance').startup(this);
//                }

//                /** Optionally call jGrowl instance methods, or just raise a normal notification **/
//                if ($.isFunction($(this).data('jGrowl.instance')[m])) {
//                    $(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'), $.makeArray(args).slice(1));
//                } else {
//                    $(this).data('jGrowl.instance').create(m, o);
//                }
//            });
//        };
//    };

//    $.extend($.fn.jGrowl.prototype, {

//        /** Default JGrowl Settings **/
//        defaults: {
//            pool: 0,
//            header: '',
//            group: '',
//            sticky: false,
//            position: 'top-right',
//            glue: 'after',
//            theme: 'default',
//            themeState: 'highlight',
//            corners: '10px',
//            check: 250,
//            life: 3500,
//            cssStyle: '',
//            closeDuration: 'normal',
//            openDuration: 'normal',
//            easing: 'swing',
//            closer: true,
//            closeTemplate: '&times;',
//            closerTemplate: '<div>[ close all ]</div>',
//            log: function(e, m, o) { },
//            beforeOpen: function(e, m, o) { },
//            afterOpen: function(e, m, o) { },
//            open: function(e, m, o) { },
//            beforeClose: function(e, m, o) { },
//            close: function(e, m, o) { },
//            animateOpen: {
//                opacity: 'show'
//            },
//            animateClose: {
//                opacity: 'hide'
//            }
//        },

//        notifications: [],

//        /** jGrowl Container Node **/
//        element: null,

//        /** Interval Function **/
//        interval: null,

//        /** Create a Notification **/
//        create: function(message, o) {
//            var o = $.extend({}, this.defaults, o);

//            /* To keep backward compatibility with 1.24 and earlier, honor 'speed' if the user has set it */
//            if (typeof o.speed !== 'undefined') {
//                o.openDuration = o.speed;
//                o.closeDuration = o.speed;
//            }

//            this.notifications.push({ message: message, options: o });

//            o.log.apply(this.element, [this.element, message, o]);
//        },

//        render: function(notification) {
//            var self = this;
//            var message = notification.message;
//            var o = notification.options;

//            // Support for jQuery theme-states, if this is not used it displays a widget header
//            o.themeState = (o.themeState == '') ? '' : 'ui-state-' + o.themeState;

//            var notification = $(
//				'<div class="jGrowl-notification ' + o.themeState + ' ui-corner-all' +
//				((o.group != undefined && o.group != '') ? ' ' + o.group : '') + '" style="' + o.cssStyle + '">' +
//				'<div class="jGrowl-close">' + o.closeTemplate + '</div>' +
//				'<div class="jGrowl-header">' + o.header + '</div>' +
//				'<div class="jGrowl-message">' + message + '</div></div>'
//			).data("jGrowl", o).addClass(o.theme).children('div.jGrowl-close').bind("click.jGrowl", function() {
//			    $(this).parent().trigger('jGrowl.close', ['click1']);
//			}).parent();
//            //            notification.hover(function() {
//            //                $(this).stop().animate({ opacity: 1 },100);
//            //            },
//            //			function() {
//            //            $(this).stop().animate({ opacity: 0.8 }, 100);
//            //			});

//            /** Notification Actions **/
//            $(notification).bind("mouseover.jGrowl", function() {
//                $('div.jGrowl-notification', self.element).data("jGrowl.pause", true);
//                if ($(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined) { $('div.jGrowl-notification', self.element).css({ opacity: 1 }).stop(); }
//            }).bind("mouseout.jGrowl", function() {
//                $('div.jGrowl-notification', self.element).data("jGrowl.pause", false);
//            }).bind('jGrowl.beforeOpen', function() {
//                if (o.beforeOpen.apply(notification, [notification, message, o, self.element]) != false) {
//                    $(this).trigger('jGrowl.open');
//                }
//            }).bind('jGrowl.open', function() {
//                if (o.open.apply(notification, [notification, message, o, self.element]) != false) {
//                    if (o.glue == 'after') {
//                        $('div.jGrowl-notification:last', self.element).after(notification);
//                    } else {
//                        $('div.jGrowl-notification:first', self.element).before(notification);
//                    }

//                    $(this).animate(o.animateOpen, 10, o.easing, function() {
//                        // Fixes some anti-aliasing issues with IE filters.
//                        if ($.browser.msie && (parseInt($(this).css('opacity'), 10) === 1 || parseInt($(this).css('opacity'), 10) === 0))
//                            this.style.removeAttribute('filter');

//                        if ($(this).data("jGrowl") != null) // Happens when a notification is closing before it's open.
//                            $(this).data("jGrowl").created = new Date();

//                        $(this).trigger('jGrowl.afterOpen');
//                    });
//                }
//            }).bind('jGrowl.afterOpen', function() {
//                o.afterOpen.apply(notification, [notification, message, o, self.element]);
//            }).bind('jGrowl.beforeClose', function() {
//                if (o.beforeClose.apply(notification, [notification, message, o, self.element]) != false)
//                    $(this).trigger('jGrowl.close', ['bClose1']);
//            }).bind('jGrowl.close', function(_ev, _stype) {
//                // Pause the notification, lest during the course of animation another close event gets called.
//                $(this).data('jGrowl.pause', true);
//                if (_stype == 'click1') {
//                    $(this).hide();
//                    if ($.isFunction(o.close)) {
//                        if (o.close.apply(notification, [notification, message, o, self.element]) !== false)
//                            $(this).remove();
//                    } else {
//                        $(this).remove();
//                    }
//                }
//                $(this).animate(o.animateClose, o.closeDuration, o.easing, function() {
//                    if ($.isFunction(o.close)) {
//                        if (o.close.apply(notification, [notification, message, o, self.element]) !== false)
//                            $(this).remove();
//                    } else {
//                        $(this).remove();
//                    }
//                });
//            }).trigger('jGrowl.beforeOpen');

//            /** Optional Corners Plugin **/
//            if (o.corners != '' && $.fn.corner != undefined) $(notification).corner(o.corners);

//            /** Add a Global Closer if more than one notification exists **/
//            if ($('div.jGrowl-notification:parent', self.element).size() > 1 &&
//				 $('div.jGrowl-closer', self.element).size() == 0 && this.defaults.closer != false) {
//                $(this.defaults.closerTemplate).addClass('jGrowl-closer ' + this.defaults.themeState + ' ui-corner-all').addClass(this.defaults.theme)
//					.appendTo(self.element).animate(this.defaults.animateOpen, this.defaults.speed, this.defaults.easing)
//					.bind("click.jGrowl", function() {
//					    $(this).siblings().trigger("jGrowl.beforeClose");

//					    if ($.isFunction(self.defaults.closer)) {
//					        self.defaults.closer.apply($(this).parent()[0], [$(this).parent()[0]]);
//					    }
//					});
//            };
//        },

//        /** Update the jGrowl Container, removing old jGrowl notifications **/
//        update: function() {
//            $(this.element).find('div.jGrowl-notification:parent').each(function() {
//                if ($(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined &&
//					 ($(this).data("jGrowl").created.getTime() + parseInt($(this).data("jGrowl").life)) < (new Date()).getTime() &&
//					 $(this).data("jGrowl").sticky != true &&
//					 ($(this).data("jGrowl.pause") == undefined || $(this).data("jGrowl.pause") != true)) {

//                    // Pause the notification, lest during the course of animation another close event gets called.
//                    $(this).trigger('jGrowl.beforeClose');
//                }
//            });
//            if (this.notifications.length > 0 &&
//				 (this.defaults.pool == 0 || $(this.element).find('div.jGrowl-notification:parent').size() < this.defaults.pool))
//                this.render(this.notifications.shift());

//            if ($(this.element).find('div.jGrowl-notification:parent').size() < 2) {
//                $(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose, this.defaults.speed, this.defaults.easing, function() {
//                    $(this).remove();
//                });
//            }
//        },

//        /** Setup the jGrowl Notification Container **/
//        startup: function(e) {
//            this.element = $(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');
//            this.interval = setInterval(function() {
//                $(e).data('jGrowl.instance').update();
//            }, parseInt(this.defaults.check));

//            if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) {
//                $(this.element).addClass('ie6');
//            }
//        },

//        /** Shutdown jGrowl, removing it and clearing the interval **/
//        shutdown: function() {
//            $(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();
//            clearInterval(this.interval);
//        },

//        close: function() {
//            $(this.element).find('div.jGrowl-notification').each(function() {
//                $(this).trigger('jGrowl.beforeClose');
//            });
//        }
//    });

//    /** Reference the Defaults Object for compatibility with older versions of jGrowl **/
//    $.jGrowl.defaults = $.fn.jGrowl.prototype.defaults;

//})(jQuery);


//$.jGrowl.defaults.closer = false;
//function jMsg(_sHeader, _sMsg, _oParam) {
//    var _oParam = $.extend({}, {
//        closer: true,
//        glue: 'before',
//        closeDuration: 3000,
//        openDuration: 10,
//        header: _sHeader
//    }, _oParam);
//    $.jGrowl(_sMsg, _oParam);
//};
function DelTooli(_sTid) {
    if ($('#' + _sTid).size() > 0) {
        $('#' + _sTid).remove();
    }
};
function AddTooli(_sTid, _sHtml) {
    if ($('#divjToolbar1').size() == 0) {
        $('<ul id="divjToolbar1" style="   "></ul>').addClass('divjToolbar1 bottom-right').css({ opacity: 0.0 }).appendTo('body');
    }
    if ($('#' + _sTid).size() == 0) {
        var sHtmlt1 = '<li id="' + _sTid + '" style="">' + _sHtml + '</li>';
        $('#divjToolbar1').append(sHtmlt1);
    } else {
        $('#' + _sTid).empty().html('').html(_sHtml);
    }
    if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) {
        $('#divjToolbar1').addClass('ie6');
    }
    var iwidthtem = 5;
    $("#divjToolbar1 li").each(function() {
        iwidthtem = $(this).outerWidth() + iwidthtem + 4;
    });
    if (iwidthtem > 5) {
        $('#divjToolbar1').width(iwidthtem).css({ opacity: 0.9 });
    }
};
//function doShowPageJobList(sCid, sId) {
//    GtGrid1Action = "doShowPageJobList";
//    var opart = GetGtParam();
//    opart.AddCell("SHOW_PAGE_JOB_L_CID", sCid);
//    opart.AddCell("SHOW_PAGE_JOB_L_ID", sId);
//    ajaxComm(opart, null, null, null, true);
//    GtGrid1Action = "";
//};
function doChangeJobpstautss(sId, sSeqNo, sNewSt) {
    if (sNewSt == "0") {
    } 
//    else if (sNewSt == "3") {
//        pShowDlg('wfFwsCsEObServicePlanRejectHandling1', { page: shUrlBase + "Fws/EOB/wfFwsCsEObServicePlanReject.aspx?ID=" + sId + "&OP=" + sOpModle, title: "作业拒绝受理操作", width: '88%', height: '86%' });
//    } else if (sNewSt == "5") {
//        pShowDlg('wfFwsCsEObServicePlanAgreeTermi1', { page: shUrlBase + "Fws/EOB/wfFwsCsEObServicePlanAgreeTermi.aspx?ID=" + sId + "&OP=" + sOpModle, title: "作业终止处理操作", width: '88%', height: '86%' });
//    } 
    else if (sNewSt == "T2") {
        pShowDlg('wfFwsCsEObServicePlanTlog21', { page: shUrlBase + "Fws/EOB/wfFwsCsEObServicePlanTlog2.aspx?ID=" + sId + "&OP=" + sOpModle, title: "联系操作人员", width: '88%', height: '86%' });
    } else if (sNewSt == "T3") {
        pShowDlg('wfFwsCsEObServicePlanTlog31', { page: shUrlBase + "Fws/EOB/wfFwsCsEObServicePlanTlog3.aspx?ID=" + sId + "&OP=" + sOpModle, title: "联系客服人员", width: '88%', height: '86%' });
    } else {
        GtGrid1Action = "doChangeJobpstautss";
        var opart = GetGtParam();
        opart.AddCell("SHOW_PAGE_JOB_L_NO", sSeqNo);
        opart.AddCell("SHOW_PAGE_JOB_L_NS", sNewSt);
        opart.AddCell("SHOW_PAGE_JOB_L_ID", sId);
        ajaxComm(opart, null, null, null);
        GtGrid1Action = "";
    }
};
function doSetJobpstautsMenuShows() {
    //    $('#sJobStListBtnSpanel211').poshytip({ content: $('#sJobStListSpanel211')[0] });
    $('#sJobStListBtnSpanel211').poshytip({ content: $('#sJobStListSpanel211').html() });
//    Tipped.create('#sJobStListBtnSpanel211', $('#sJobStListSpanel211')[0], { skin: 'cloud', hook: 'bottomright', fadeIn: 10, fadeOut: 10, showDelay: 15, hideDelay: 25 });
};
function doPageJobBeClick(sId, sWid) {
    GtGrid1Action = "doPageJobBeClick";
    var opart = GetGtParam();
    opart.AddCell("SHOW_PAGE_JOB_L_WID", sWid);
    opart.AddCell("SHOW_PAGE_JOB_L_ID", sId);
    ajaxComm(opart, null, null, null, true);
    GtGrid1Action = "";
};
function ShowPageJobList(sCid, sId, sWid, sWnme, sIsCmp, sIsCle, sIsCCle, sAllowDo, sAllowClick, sRmk, sIsEmergency, sPEnddt, sAEnddt, sAEndUsr) {
    var $sCidtem1 = $("#" + sCid);
    if ($sCidtem1.size() > 0) {
        var $sCidtemC2 = $sCidtem1.find(".jobitemc");
        if ($sCidtemC2.size() <= 0) {
            $sCidtem1.append($("<span style='color:Green;font-weight:bold;'>作业任务项:</span><a class='cIsEmergency icon icon-thumb_up' style='display:none;' herf='javascript:void(0);return false;' onclick=';' >" + sIsEmergency + "</a><span class='jobitemc'></span><span class='jobRmkbz'></span>"));
            $sCidtemC2 = $sCidtem1.find(".jobitemc");
            //            if (sRmk) { $sCidtem1.find(".jobRmkbz").html(' 要求:<input name="jobRmkbz' + sCid + '" value="' + sRmk + '" readonly="readonly" type="text" maxlength="200" id="jobRmkbz' + sCid + '" class="inputtxt" style="width:120px;" />'); }
        }
        var sHtmltem1 = ($sCidtem1.find("   span[id^='job_']").size() + 1) + '. ' + sWnme + (sIsCmp == "True" ? "<span class='icon icon-tick'></span>" : "");
        if (sAllowDo === "True") { sHtmltem1 = '<span class="icon icon-user"></span>' + sHtmltem1; }
        sHtmltem1 = '' + '--><span id="job_' + sWid + '" class="custnode" style="">' + sHtmltem1 + '</span>';
        $sCidtemC2.append(sHtmltem1);
        if (sAllowClick === "True") {
            $("#job_" + sWid).hover(function() { $(this).addClass("ExecHover"); }, function() { $(this).removeClass("ExecHover"); })
            .click(function() {
                doPageJobBeClick(sId, sWid);
            });
        }
        if (sIsEmergency != "") { $sCidtem1.find(".cIsEmergency").show(); }
        sHtmltem1 = "";
        if (sPEnddt) { sHtmltem1 += ' 计划完成时间:' + sPEnddt; }
        if (sAEnddt) { sHtmltem1 += ' 实际完成时间:' + sAEnddt; }
        if (sAEndUsr) { sHtmltem1 += ' 实际执行人:' + sAEndUsr; }
        if (sIsCle == "True") { sHtmltem1 += ' 正在被取消'; }
        if (sHtmltem1) {
            $("#job_" + sWid).poshytip({ content: sHtmltem1 });
//            Tipped.create("#job_" + sWid, sHtmltem1, {
//                skin: 'cloud'
//            });
        }
    }
};
function doNewRemind() {
    pShowDlg("doNewRemind1", { page: shUrlBase + "User/wfSysUserRemindEditor.aspx?MODE=ADD", title: "新增备忘录--", width: "82%", height: "82%" });
};
function ShowTipBytile(sTitle) {
    GtGrid1Action = "doShowTipBytile";
    var opart = GetGtParam();
    opart.AddCell("TITLE_TXT", sTitle);
    ajaxComm(opart, null, null, null, true);
    GtGrid1Action = "";
};
function AddBaseTool() {
    GtGrid1Action = "doShowAddBaseTool";
    var opart = GetGtParam();
    ajaxComm(opart, null, null, null, true);
    GtGrid1Action = "";
    //    var sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">公文包</a>';
    //    AddTooli('btlGwbShow', sltem11);
    //    sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">备忘录</a>';
    //    AddTooli('btlBwlShow', sltem11);
    //    sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">任务</a>';
    //    AddTooli('btlJobShow', sltem11);
    //    sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">消息</a>';
    //    AddTooli('btlMsgShow', sltem11);
    //    sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">公告</a>';
    //    AddTooli('btlPubNShow', sltem11);
    //    sltem11 = '<a href="javascript:void(0);return false;" onclick="btnDo(\'btnShowGZ\');">提示</a>';
    //    AddTooli('btlTipShow', sltem11);
    //    Tipped.create("#btlGwbShow", "Tooltips look the same across browsers!", {
    //        skin: 'cloud' 
    //    });
};

////cooke
//jQuery.cookie = function(name, value, options) {
//    if (typeof value != 'undefined') { // name and value given, set cookie
//        options = options || {};
//        if (value === null) {
//            value = '';
//            options.expires = -1;
//        }
//        var expires = '';
//        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
//            var date;
//            if (typeof options.expires == 'number') {
//                date = new Date();
//                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
//            } else {
//                date = options.expires;
//            }
//            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
//        }
//        // CAUTION: Needed to parenthesize options.path and options.domain
//        // in the following expressions, otherwise they evaluate to undefined
//        // in the packed version for some reason...
//        var path = options.path ? '; path=' + (options.path) : '';
//        var domain = options.domain ? '; domain=' + (options.domain) : '';
//        var secure = options.secure ? '; secure' : '';
//        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
//    } else { // only name given, get cookie
//        var cookieValue = null;
//        if (document.cookie && document.cookie != '') {
//            var cookies = document.cookie.split(';');
//            for (var i = 0; i < cookies.length; i++) {
//                var cookie = jQuery.trim(cookies[i]);
//                // Does this cookie string begin with the name we want?
//                if (cookie.substring(0, name.length + 1) == (name + '=')) {
//                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
//                    break;
//                }
//            }
//        }
//        return cookieValue;
//    }
//};

////everyTime
//jQuery.fn.extend({
//    everyTime: function(interval, label, fn, times) {
//        return this.each(function() {
//            jQuery.timer.add(this, interval, label, fn, times);
//        });
//    },
//    oneTime: function(interval, label, fn) {
//        return this.each(function() {
//            jQuery.timer.add(this, interval, label, fn, 1);
//        });
//    },
//    stopTime: function(label, fn) {
//        return this.each(function() {
//            jQuery.timer.remove(this, label, fn);
//        });
//    }
//});

//jQuery.extend({
//    timer: {
//        global: [],
//        guid: 1,
//        dataKey: "jQuery.timer",
//        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
//        powers: {
//            // Yeah this is major overkill...
//            'ms': 1,
//            'cs': 10,
//            'ds': 100,
//            's': 1000,
//            'das': 10000,
//            'hs': 100000,
//            'ks': 1000000
//        },
//        timeParse: function(value) {
//            if (value == undefined || value == null)
//                return null;
//            var result = this.regex.exec(jQuery.trim(value.toString()));
//            if (result[2]) {
//                var num = parseFloat(result[1]);
//                var mult = this.powers[result[2]] || 1;
//                return num * mult;
//            } else {
//                return value;
//            }
//        },
//        add: function(element, interval, label, fn, times) {
//            var counter = 0;

//            if (jQuery.isFunction(label)) {
//                if (!times)
//                    times = fn;
//                fn = label;
//                label = interval;
//            }

//            interval = jQuery.timer.timeParse(interval);

//            if (typeof interval != 'number' || isNaN(interval) || interval < 0)
//                return;

//            if (typeof times != 'number' || isNaN(times) || times < 0)
//                times = 0;

//            times = times || 0;

//            var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

//            if (!timers[label])
//                timers[label] = {};

//            fn.timerID = fn.timerID || this.guid++;

//            var handler = function() {
//                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
//                    jQuery.timer.remove(element, label, fn);
//            };

//            handler.timerID = fn.timerID;

//            if (!timers[label][fn.timerID])
//                timers[label][fn.timerID] = window.setInterval(handler, interval);

//            this.global.push(element);

//        },
//        remove: function(element, label, fn) {
//            var timers = jQuery.data(element, this.dataKey), ret;

//            if (timers) {

//                if (!label) {
//                    for (label in timers)
//                        this.remove(element, label, fn);
//                } else if (timers[label]) {
//                    if (fn) {
//                        if (fn.timerID) {
//                            window.clearInterval(timers[label][fn.timerID]);
//                            delete timers[label][fn.timerID];
//                        }
//                    } else {
//                        for (var fn in timers[label]) {
//                            window.clearInterval(timers[label][fn]);
//                            delete timers[label][fn];
//                        }
//                    }

//                    for (ret in timers[label]) break;
//                    if (!ret) {
//                        ret = null;
//                        delete timers[label];
//                    }
//                }

//                for (ret in timers) break;
//                if (!ret)
//                    jQuery.removeData(element, this.dataKey);
//            }
//        }
//    }
//});

//jQuery(window).bind("unload", function() {
//    jQuery.each(jQuery.timer.global, function(index, item) {
//        jQuery.timer.remove(item);
//    });
//});













/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/

; (function ($) {

    $.fn.extend({
        autocomplete: function (urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function (value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function () {
                new $.Autocompleter(this, options);
            });
        },
        result: function (handler) {
            return this.bind("result", handler);
        },
        search: function (handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function () {
            return this.trigger("flushCache");
        },
        setOptions: function (options) {
            return this.trigger("setOptions", [options]);
        },
        setAutoSearch: function (blupd) {
            return this.trigger("setAutoSearch", [blupd]);
        },
        unautocomplete: function () {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function (input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
        $input.attr("relrowid", 'oldrelrowid').attr("seekrowid", 'oldrelrowid');
        var allowUpdate = true;
        var timeout;
        var timeoutkey;
        var previousValue = null;
        var preSelValue = '';
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false,
            isSelect: false,
            isToolHover: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function () {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
            if ($(this).attr('readOnly')) { return; }
            // a keypress means the input has focus
            // avoids issue where input had focus before the autocomplete was applied
            hasFocus = 1;
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon                                       
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    hideResults(options.autoFill); //select.hide();
                    break;

                default:
                    allowUpdate = false;
                    clearTimeout(timeoutkey);
                    timeoutkey = setTimeout(function () {
                        onChange();
                    }, 1300);
                    break;
            }
        }).focus(function () {
            if ($(this).attr('readOnly')) { return; } //$('#ssssyysss').html(''+$(this).val());
            //            if (previousValue === null || previousValue == '') {  }if(preSelValue==''){ }
            previousValue = $input.val(); preSelValue = $input.val();
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            $input.attr("oldrelrowid", $input.attr('relrowid'));
            hasFocus++;
        }).blur(function () {
            if ($(this).attr('readOnly')) { return; }
            hasFocus = 0; //$('#ffffff').html('a'+hasFocus);//$('#sssssss').html(''+$(this).val());
            if (config.mouseDownOnSelect == '') {//$('#ffffff').html('na'+hasFocus);
                hideResults(options.autoFill);
            }
            preSelValue = '';
            previousValue = '';
            config.mouseDownOnSelect = false;
        }).dblclick(function () {
            if ($(this).attr('readOnly')) { return; } //$('#ffffff').html('ab'+hasFocus);$('#sssssss').html(''+$(this).val());
            // show select when clicking in a focused field
            if (hasFocus++ && !select.visible()) {
                //$('#ffffff').html('ap'+hasFocus);
                allowUpdate = false;
                clearTimeout(timeoutkey);
                timeoutkey = setTimeout(function () {
                    onChange(0, true);
                }, 500);
            }
        }).bind("search", function () {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                if (q == '') { return; } if ($input.attr('seekrowid') != $input.attr('relrowid')) { return; }
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].value.toLowerCase().replace(/(^\s*)/g, "").replace(/(\s*$)/g, "") == q.toLowerCase() || data[i].result.toLowerCase().replace(/(^\s*)/g, "").replace(/(\s*$)/g, "") == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else
                    onResult(result); // $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function (i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function () {
            cache.flush();
        }).bind("setOptions", function () {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("setAutoSearch", function () {
            allowUpdate = arguments[1];
        }).bind("unautocomplete", function () {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete").bind("input", function () {
                // @hack by liqt:support for inputing  chinese characters  in firefox   
                onChange(0, true);
            }); ;
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected) {
                hideResults(options.autoFill);
                return false;
            }
            //            if(!allowUpdate){return;}
            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    var seperator = options.multipleSeparator.length;
                    var cursorAt = $(input).selection().start;
                    var wordAt, progress = 0;
                    $.each(words, function (i, word) {
                        progress += word.length;
                        if (cursorAt <= progress) {
                            wordAt = i;
                            return false;
                        }
                        progress += seperator;
                    });
                    words[wordAt] = v;
                    // TODO this should set the cursor to the right position, but it gets overriden somewhere
                    //$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
                    v = words.join(options.multipleSeparator);
                }
                v += options.multipleSeparator;
            }
            if (v == '') {
                debugger;
            }
            $input.val(v);
            onResult(selected);
            hideResults(true);
            //            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onResult(result) {//debugger;
            if (!allowUpdate) { return; }
            if ($input.attr('seekrowid') != $input.attr('relrowid')) { config.isSelect = true; return; }
            if (!result) {
                if (options.multiple) {
                    var words = trimWords($input.val()).slice(0, -1);
                    $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "")); //preSelValue = $input.val();//preSelValue='';
                }
                else {
                    if ($input.val() == '') { $input.trigger("result", null); } // else if (options.mustMatch) { $input.val(preSelValue);}
                    //                    if (options.mustMatch) {
                    //                        $input.val(preSelValue);
                    //                    }
                    //                    $input.trigger("result", null);
                }
            } else {//debugger;
                $input.trigger("result", result && [result.data, result.value]); preSelValue = $input.val();
            }
            config.isSelect = true;
        }

        function onChange(crap, skipPrevCheck) {//debugger;
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }
            allowUpdate = true;
            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue === previousValue)
                return;
            config.isSelect = false;
            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value)
                return [""];
            if (!options.multiple)
                return [$.trim(value)];
            return $.map(value.split(options.multipleSeparator), function (word) {
                return $.trim(value).length ? $.trim(word) : null;
            });
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            if (words.length == 1)
                return words[0];
            var cursorAt = $(input).selection().start;
            if (cursorAt == value.length) {
                words = trimWords(value)
            } else {
                words = trimWords(value.replace(value.substring(cursorAt), ""));
            }
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue, datar) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                if (previousValue === null) { previousValue = $(input).val(); }
                if (sValue.substring(0, previousValue.length) == $input.val()) {
                    $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                }
                // select the portion of the value not typed by the user (so the next character will erase)
                $(input).selection(previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults(isOnlyHide) {
            //            if ($input.val() == "") {
            clearTimeout(timeoutkey); //debugger;
            //                onChange();
            clearTimeout(timeout);
            hideResultsNow(isOnlyHide);
            //            } else {
            //                clearTimeout(timeout);
            //                timeout = setTimeout(function () { hideResultsNow(isOnlyHide); }, 300);
            //            }
        };

        function hideResultsNow(isHadSelected) {//debugger;
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            //            if (isHadSelected) {
            //                return;
            //            }
            //            if (!config.isSelect &&wasVisible) {
            if (!isHadSelected) {
                if ($input.attr('oldrelrowid') != $input.attr('relrowid')) { return; }
                if ($input.val() == '') { $input.trigger("result", null); preSelValue = ''; previousValue = ''; } else if (options.mustMatch) { if (preSelValue == '') { ; } $input.val(preSelValue); }

            }
            //            if (!isHadSelected) {
            // call search and run callback
            //                $input.search(
            //				function (result) {
            //				    // if no value found, clear the input box
            //				    onResult(result);
            //				    //				    if (!result) {
            //				    //				        if (options.multiple) {
            //				    //				            var words = trimWords($input.val()).slice(0, -1);
            //				    //				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
            //				    //				        }
            //				    //				        else {
            //				    //				            if (options.mustMatch) {
            //				    //				                $input.val("");
            //				    //				            }
            //				    //				            $input.trigger("result", null);
            //				    //				        }
            //				    //				    } else {
            //				    //				        $input.trigger("result", result && [result.data, result.value]);
            //				    //				    }
            //				}
            //			);
            //            }
        };

        function receiveData(q, data) {
            stopLoading();
            select.display(data, q);
            if (data && data.length && hasFocus) {
                autoFill(q, data[0].result, data[0]);
                select.show();
            } else {
                //                config.isSelect = true;
                //                onResult(data?data[0]:data);
                //                hideResultsNow();
            }
            select.show();
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();

            $input.attr("seekrowid", $input.attr('relrowid'));
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function (key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });
                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function (data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 0,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function (row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ",",
        highlight: function (value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 220
    };

    $.Autocompleter.Cache = function (options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function (i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function (q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function (i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                        return data[q];
                    } else
                        if (options.matchSubset) {
                            for (var i = q.length - 1; i >= options.minChars; i--) {
                                var c = data[q.substr(0, i)];
                                if (c) {
                                    var csub = [];
                                    $.each(c, function (i, x) {
                                        if (matchSubset(x.value, q)) {
                                            csub[csub.length] = x;
                                        }
                                    });
                                    return csub;
                                }
                            }
                        }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function (options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list,
		pagetoolb;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>").css("z-index", parseInt(new Date().getTime() / 1000) + 300)
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function (event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function (event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                if (!$(input).is(":hidden")) { input.focus(); }
                return false;
            }).mousedown(function () {
                config.mouseDownOnSelect = true;
                if (!$(input).is(":hidden")) { input.focus(); }
            }).mouseup(function () {
                config.mouseDownOnSelect = false;
            }).mouseout(function () {
                if (!$(input).is(":hidden")) { input.focus(); }
            });
            //            pagetoolb = $("<ul/>").appendTo(element);
            //            var tem12311 = $('<a herf="javascript:void(0);return false;">[ 关闭 ]</a>').click(function(event) {
            //                hideResultsNow(true); alert('da');
            //            }
            //            );
            //            $("<li/>").appendTo(pagetoolb).append(tem12311);
            //            pagetoolb.hover(function() {
            //                config.isToolHover = true;
            //            },
            //            function() {
            //                config.isToolHover = false;
            //            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            if (listItems.length <= 0) { return; }
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function () {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            if (max == 0) {
                list.html('<font style="color:red;font-size:10pt;padding: 2px;"> 未找到记录，请重新输入关键字！</font>');
            }
            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function (d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function () {
                moveSelect(1);
            },
            prev: function () {
                moveSelect(-1);
            },
            pageUp: function () {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function () {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function () {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function () {
                return element && !element.is(":hidden");
            },
            current: function () {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function () {
                var offset = $(input).offset();
                var iToptem1 = offset.top + input.offsetHeight; //outerHeight
                $(element).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        maxWidth: options.width,
                        overflow: 'auto'
                    });
                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function () {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
                var outerhtem1 = $(element).outerHeight(); if (outerhtem1 > 222) { outerhtem1 = 222; }
                if ($(window).height() + $(document).scrollTop() < iToptem1 + outerhtem1) {
                    iToptem1 = offset.top - outerhtem1;
                }
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: iToptem1,
                    left: offset.left
                });
            },
            selected: function () {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function () {
                list && list.empty();
            },
            isFocus: function () {
                return element && element.is(':focus');
            },
            unbind: function () {
                element && element.remove();
            }
        };
    };

    $.fn.selection = function (start, end) {
        if (start !== undefined) {
            return this.each(function () {
                if (this.createTextRange) {
                    var selRange = this.createTextRange();
                    if (end === undefined || start == end) {
                        selRange.move("character", start);
                        selRange.select();
                    } else {
                        selRange.collapse(true);
                        selRange.moveStart("character", start);
                        selRange.moveEnd("character", end);
                        selRange.select();
                    }
                } else if (this.setSelectionRange) {
                    this.setSelectionRange(start, end);
                } else if (this.selectionStart) {
                    this.selectionStart = start;
                    this.selectionEnd = end;
                }
            });
        }
        var field = this[0];
        if (field.createTextRange) {
            var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
            range.text = teststring;
            var caretAt = field.value.indexOf(teststring);
            field.value = orig;
            this.selection(caretAt, caretAt + textLength);
            return {
                start: caretAt,
                end: caretAt + textLength
            }
        } else if (field.selectionStart !== undefined) {
            return {
                start: field.selectionStart,
                end: field.selectionEnd
            }
        }
    };

})(jQuery);




//jquery_autocomplete
function jqLookup(jludomp, jupdataType, _extraParams, _OnSelected) {
    var $combtem1;
    var sId = '';
    if (typeof (jludomp) == "string") {
        $combtem1 = $("#" + jludomp);
        sId = jludomp;
    } else {
        $combtem1 = $(jludomp);
        sId = jludomp.id;
    }
    if (_extraParams && _extraParams.extraParams) {
        _extraParams.extraParams.STYPE = jupdataType;
    }
    var optionsextraParams = $.extend({}, {
        extraParams: {
            STYPE: jupdataType,
            TotalRowNum: -1,
            PageSize: 20,
            TotalPageNum: -1,
            PageNum: -1,
            StartRowNum: -1,
            EndRowNum: -1
            //        country: function() { return $("#txtBK_NO").val(); }
        },
        max: 50,
        minChars: 0,
        cacheLength: 0,
        width: 310,
        delay: 1200,
        matchContains: "word",
        autoFill: false,
        matchContains: true,
        mustMatch: true,
        dFieldList: null,
        sTextField: 'V_NME',
        sValueField: 'V_CDE',
        R_F_T: '',
        R_F_V: '',
        sShowField: 'V_NME',
        parse: function(reqdata) {
            var datatem1, datatem2;
            var datatem = eval(reqdata);
            if (datatem.length > 0) {
                datatem1 = datatem[0];
            }
            if (datatem1.jmsg) {
                jMsg('下拉选择错误', datatem1.jmsg);
                return [];
            }
            if (datatem.length > 1) {
                this.dFieldList = datatem[1];
            }
            if (datatem1.sTextField) {
                this.sTextField = datatem1.sTextField;
            }
            if (datatem1.sValueField) {
                this.sValueField = datatem1.sValueField;
            }
            var parsed = [];
            var rows = datatem1.rows;
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row) {
                    row = row;
                    parsed[parsed.length] = {
                        data: row,
                        value: row[this.sValueField],
                        result: this.formatResult && this.formatResult(row, row[this.sShowField]) || row[this.sShowField]
                    };
                }
            }
            return parsed;
        },
        formatItem: function(row, i, max) {
            var sHtmltem = "<font color='gray'>" + i + "</font>: " + row[this.sTextField] + " 【<font color='blue'>" + row[this.sValueField] + "</font>】";
            var sHtmltem2 = "";
            if (this.dFieldList && this.dFieldList.length > 0) {
                for (var i = 0; i < this.dFieldList.length; i++) {
                    var Flrow = this.dFieldList[i];
                    if (Flrow.id && Flrow.id != this.sValueField && Flrow.id != this.sTextField) {
                        //                        if (sHtmltem2 == "") {
                        //                            sHtmltem2 += "<br><span style='color:gray;'>";
                        //                        }
                        sHtmltem2 += "<br><span style='color:gray;padding-left:20px;'>" + Flrow.header + ": &lt;" + row[Flrow.id] + "&gt; " + "</span>";
                    }
                }
            }
            //            sHtmltem2 = "";
            //            if (this.dFieldList && this.dFieldList.length > 0) {
            //                for (var i = 0; i < this.dFieldList.length; i++) {
            //                    var Flrow = this.dFieldList[i];
            ////                    if (Flrow.id && Flrow.id != this.sValueField && Flrow.id != this.sTextField) {
            //                        //                        if (sHtmltem2 == "") {
            //                        //                            sHtmltem2 += "<br><span style='color:gray;'>";
            //                        //                        }
            //                    sHtmltem2 += "<div style='float:left;word-break: keep-all;white-space: nowrap;height:20px;overflow: hidden;text-overflow: ellipsis;width:" + Flrow.width + "px;'>" + row[Flrow.id] + "</div>";
            ////                    }
            //                }
            //            }
            if (sHtmltem2 != "") {
                //                sHtmltem2 += "</span>";
                sHtmltem = sHtmltem + sHtmltem2 + " ";
            }
            if (i == max) {
                //                            sHtmltem += "<span id='sdfasddfa112'></span>";
                //                            sHtmltem += "<script type=\"text/javascript\">";
                //                            sHtmltem += "alert($('#jluBOOKING_PARTNER_CDE').html());";
                ////                            sHtmltem += "$('#sdfasddfa112').parent().parent().append($('<span >dfass</span>'));";
                //                            sHtmltem += "<\/script>";
                //                sHtmltem += "<br><div onclick='return false;'><a href='javascript:void(0)' onclick='$(\"#jluBOOKING_PARTNER_CDE\").search();return false;'  >" + "刷新" + "</a></div>";
            }
            return sHtmltem;
        },
        formatMatch: function(row, i, max) {
            return row[this.sShowField] + " " + row[this.sTextField] + " " + row[this.sValueField];
        },
        formatResult: function(row) {
            //            _OnSelected && _OnSelected(row);
            return row[this.sShowField];
        }
    }, _extraParams);

    if (sId.substr(0, 3) == 'txt') {
        optionsextraParams.sShowField = optionsextraParams.sValueField;
    }

    if (optionsextraParams.sShowField != optionsextraParams.sTextField && optionsextraParams.sShowField != optionsextraParams.sValueField) {
        optionsextraParams.sShowField = optionsextraParams.sTextField;
    }
    $combtem1.attr("sTextField", optionsextraParams.sTextField);
    $combtem1.attr("sValueField", optionsextraParams.sValueField);
    $combtem1.attr("sShowField", optionsextraParams.sShowField);
    $combtem1.attr("R_F_T", optionsextraParams.R_F_T);
    $combtem1.attr("R_F_V", optionsextraParams.R_F_V);
    if ($combtem1.attr("combValue") == null || typeof $combtem1.attr("combValue") == undefined) {
        $combtem1.attr("combValue", '');
        $combtem1.attr("combText", '');
    }
    $combtem1.attr("ToolTip", '\u76F4\u63A5\u8F93\u5165\u4FE1\u606F\u8FDB\u884C\u6B65\u8FDB\u5F0F\u641C\u7D22\uFF0C\u6216\u53CC\u51FB\u663E\u793A\u4E0B\u62C9\u9009\u62E9\u6846\uFF01');

    $combtem1.autocomplete(shUrlBase + "lookupcmd.axd", optionsextraParams).result(function (e, row, value, sec) {//shUrlBase + "UserControl/ajLookUp.aspx"
        var $combctem1 = $(this);
        var valuetem = (row ? row[$combtem1.attr("sValueField")] : '');
        var texttem = (row ? row[$combtem1.attr("sTextField")] : '');
        var showtem = (row ? row[$combtem1.attr("sShowField")] : '');
//        var haschangecomb = valuetem != $combctem1.attr("combValue"); //|| texttem != $combctem1.attr("combText");
//        if (haschangecomb) {
            $combctem1.attr("combValue", valuetem).attr("combText", texttem); //
            if ($combtem1.attr("sValueField") != $combtem1.attr("sShowField")) {
                if ($combctem1.val() != showtem && optionsextraParams.mustMatch !== false) {
                    $combctem1.val(showtem);
                }
            }
            _OnSelected && _OnSelected(row, valuetem, texttem, $combctem1);
//        }
    });

};





//jquery.validationEngine-en
(function($) {
    $.fn.validationEngineLanguage = function() { };
    $.validationEngineLanguage = {
        newLang: function() {
            $.validationEngineLanguage.allRules = { "required": {    			// Add your regex rules here, you can take telephone as an example
                "regex": "none",
                "alertText": "* \u5FC5\u987B\u88AB\u586B\u5199",
                "alertTextCheckboxMultiple": "* Please select an option",
                "alertTextCheckboxe": "* This checkbox is required"
            },
                "length": {
                    "regex": "none",
                    "alertText": "*Between ",
                    "alertText2": " and ",
                    "alertText3": " characters allowed"
                },
                "maxCheckbox": {
                    "regex": "none",
                    "alertText": "* Checks allowed Exceeded"
                },
                "minCheckbox": {
                    "regex": "none",
                    "alertText": "* Please select ",
                    "alertText2": " options"
                },
                "confirm": {
                    "regex": "none",
                    "alertText": "* Your field is not matching"
                },
                "time24": {
                    "regex": /^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$/,
                    "alertText": "*  08:30"
                },
                "telephone": {
                    "regex": "/^[0-9\-\(\)\ ]+$/",
                    "alertText": "* Invalid phone number"
                },
                "email": {
                    "regex": "/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
                    "alertText": "* Invalid email address"
                },
                "ip": {
                    "regex": "/^(([1-9][0-9]?|1[0-9]{2}|2[0-5][0-9]).)(([0-9]{1,2}|1[0-9]{2}|2[0-5][0-9]).){2}([0-9]{1,2}|1[0-9]{2}|2[0-5][0-9])$/",
                    "alertText": "* IP：255.255.255.255"
                },
                "date": {
                    "regex": "/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/",
                    "alertText": "*  2001-01-01"
                },
                "onlyNumber": {
                    "regex": "/^[0-9\ ]+$/",
                    "alertText": "* \u53EA\u80FD\u8F93\u5165\u6574\u6570\u6570\u5B57"
                },
                "onlyDec": {
                    "regex": "/^(-?\\d+)(\\.\\d+)?$/",
                    "alertText": "* Decimals only"
                },
                "noSpecialCaracters": {
                    "regex": "/^[0-9a-zA-Z]+$/",
                    "alertText": "* No special caracters allowed"
                },
                "ajaxUser": {
                    "file": "validateUser.php",
                    "extraData": "name=eric",
                    "alertTextOk": "* This user is available",
                    "alertTextLoad": "* Loading, please wait",
                    "alertText": "* This user is already taken"
                },
                "ajaxName": {
                    "file": "validateUser.php",
                    "alertText": "* This name is already taken",
                    "alertTextOk": "* This name is available",
                    "alertTextLoad": "* Loading, please wait"
                },
                "onlyLetter": {
                    "regex": "/^[a-zA-Z\ \']+$/",
                    "alertText": "* Letters only"
                }
            }
        }
    }
})(jQuery);

$(window).load(function() {
    $.validationEngineLanguage.newLang()
});


//jquery.validationEngine
/*
* Inline Form Validation Engine 1.6.2, jQuery plugin
* 
* Copyright(c) 2009, Cedric Dugas
* http://www.position-relative.net
*	
* Form validation engine allowing custom regex rules to be added.
* Thanks to Francois Duquette
* Licenced under the MIT Licence
*/

(function($) {

    $.fn.validationEngine = function(settings) {
        if ($.validationEngineLanguage) {				// IS THERE A LANGUAGE LOCALISATION ?
            allRules = $.validationEngineLanguage.allRules;
        } else {
            $.validationEngine.debug("Validation engine rules are not loaded check your external file");
        }
        settings = jQuery.extend({
            allrules: allRules,
            validationEventTriggers: "blur",
            inlineValidation: true,
            returnIsValid: false,
            animateSubmit: false,
            unbindEngine: true,
            ajaxSubmit: false,
            promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
            success: false,
            failure: function() { }
        }, settings);
        $.validationEngine.settings = settings;
        //        $.validationEngine.ajaxValidArray = new Array(); // ARRAY FOR AJAX: VALIDATION MEMORY 

        if (settings.inlineValidation == true) { 		// Validating Inline ?
            if (!settings.returnIsValid) {					// NEEDED FOR THE SETTING returnIsValid
                allowReturnIsvalid = false;

                var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
                var ptem123321 = $(this);
                ptem123321.find(" input[type='text'][id^='txt'][class*=validate]").live(settings.validationEventTriggers, function(caller) {if(this.readOnly){return;} _inlinEvent(this); })
                ptem123321.find(" input[type='text'][id^='jlu'][class*=validate]").live(settings.validationEventTriggers, function(caller) { if(this.readOnly){return;}_inlinEvent(this); })
                ptem123321.find(" textarea[id^='txt'][class*=validate]").live(settings.validationEventTriggers, function(caller) {if(this.readOnly){return;} _inlinEvent(this); })
                ptem123321.find(" select[id^='dpl'][class*=validate]").live(settings.validationEventTriggers, function(caller) { _inlinEvent(this); })
                
//                $(this).find("[class*=validate]").not("[type=checkbox]").on(settings.validationEventTriggers, function(caller) { _inlinEvent(this); })
//                $(this).find("[class*=validate][type=checkbox]").on("click", function(caller) { _inlinEvent(this); })

                firstvalid = false;
            }
            function _inlinEvent(caller) {            
                $.validationEngine.settings = settings;
                if ($.validationEngine.intercept == false || !$.validationEngine.intercept) {		// STOP INLINE VALIDATION THIS TIME ONLY
                    $.validationEngine.onSubmitValid = false;
                    $.validationEngine.loadValidation(caller);
                } else {
                    $.validationEngine.intercept = false;
                }
            }
        }
        if (settings.returnIsValid) {		// Do validation and return true or false, it bypass everything;
            if ($.validationEngine.submitValidation(this, settings)) {
                //                var errstem21 = "";
                //                for (m in $.validationEngine.ArrError) {
                //                    var fname = $("#" + m).attr("fname") || m;
                //                    errstem21 += "【" + fname + "】:" + $.validationEngine.ArrError[m];
                //                }
                //                if (errstem21) { jMsg("数据校验提示", errstem21); }
                return false;
            } else {
                return true;
            }
        }
        //        $(this).bind("submit", function(caller) {   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
        //            $.validationEngine.onSubmitValid = true;
        //            $.validationEngine.settings = settings;
        //            if ($.validationEngine.submitValidation(this, settings) == false) {
        //                if ($.validationEngine.submitForm(this, settings) == true) { return false; }
        //            } else {
        //                settings.failure && settings.failure();
        //                return false;
        //            }
        //        })
        $(".formError").live("click", function() {	 // REMOVE BOX ON CLICK
            $(this).fadeOut(150, function() { $(this).remove(); });
        })
    };
    $.validationEngine = {
        defaultSetting: function(caller) {
            if ($.validationEngineLanguage) {				// IS THERE A LANGUAGE LOCALISATION ?
                allRules = $.validationEngineLanguage.allRules;
            } else {
                $.validationEngine.debug("Validation engine rules are not loaded check your external file");
            }
            settings = {
                allrules: allRules,
                validationEventTriggers: "blur",
                inlineValidation: true,
                returnIsValid: false,
                animateSubmit: true,
                unbindEngine: true,
                ajaxSubmit: false,
                promptPosition: "bottomLeft", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
                success: false,
                failure: function() { }
            }
            $.validationEngine.settings = settings;
        },
        loadValidation: function(caller, cform) {		// GET VALIDATIONS TO BE EXECUTED
            if (!$.validationEngine.settings) {
                $.validationEngine.defaultSetting()
            }
            rulesParsing = $(caller).attr('class');
            rulesRegExp = /\[(.*)\]/;
            getRules = rulesRegExp.exec(rulesParsing);
            if (getRules == null) { return ""; }
            str = getRules[1];
            pattern = /\W+/;
            result = str.split(pattern);

            var validateCalllErrMsg = $.validationEngine.validateCall(caller, result, cform);
            return validateCalllErrMsg;
        },
        validateCall: function(caller, rules, cform) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
            var promptText = ""

            if (!$(caller).attr("id")) { $.validationEngine.debug("This field have no ID attribut( name & class displayed): " + $(caller).attr("name") + " " + $(caller).attr("class")) }

            caller = caller;
            //            ajaxValidate = false;
            var callerName = $(caller).attr("name");
            //            $.validationEngine.isError = false;
            //            $.validationEngine.ArrError = $.validationEngine.ArrError || {};
            //            $.validationEngine.showTriangle = true;
            callerType = $(caller).attr("type");

            for (i = 0; i < rules.length; i++) {
                switch (rules[i]) {
                    //                    case "optional":               
                    //                        if (!$(caller).val()) {               
                    //                            $.validationEngine.closePrompt(caller);               
                    //                            return $.validationEngine.isError;               
                    //                        }               
                    //                        break;               
                    case "required":
                        _required(caller, rules);
                        break;
                    case "custom":
                        _customRegex(caller, rules, i);
                        break;
                    //                    case "ajax":               
                    //                        if (!$.validationEngine.onSubmitValid) {               
                    //                            _ajax(caller, rules, i);               
                    //                        };               
                    //                        break;               
                    case "length":
                        _length(caller, rules, i);
                        break;
                    //                    case "maxCheckbox":               
                    //                        _maxCheckbox(caller, rules, i);               
                    //                        groupname = $(caller).attr("name");               
                    //                        caller = $("input[name='" + groupname + "']");               
                    //                        break;               
                    //                    case "minCheckbox":               
                    //                        _minCheckbox(caller, rules, i);               
                    //                        groupname = $(caller).attr("name");               
                    //                        caller = $("input[name='" + groupname + "']");               
                    //                        break;               
                    //                    case "confirm":               
                    //                        _confirm(caller, rules, i);               
                    //                        break;               
                    default: ;
                };
            };
            //            radioHack();
            if (promptText) {
                linkTofield = $.validationEngine.linkTofield(caller);

                ($("div." + linkTofield).size() == 0) ? $.validationEngine.buildPrompt(caller, promptText, "error") : $.validationEngine.updatePromptText(caller, promptText);
            } else { $.validationEngine.closePrompt(caller); }
            /* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */
            /* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */
            //            function radioHack() {
            //                if ($("input[name='" + callerName + "']").size() > 1 && (callerType == "radio" || callerType == "checkbox")) {        // Hack for radio/checkbox group button, the validation go the first radio/checkbox of the group
            //                    caller = $("input[name='" + callerName + "'][type!=hidden]:first");
            //                    $.validationEngine.showTriangle = false;
            //                }
            //            }
            /* VALIDATION FUNCTIONS */
            function _required(caller, rules) {   // VALIDATE BLANK FIELD
                callerType = $(caller).attr("type");
                if (!(callerType || false)) {
                    callerType = $(caller)[0].type;
                }
                if (callerType == "text" || callerType == "password" || callerType == "textarea") {

                    if (!$(caller).val()) {
                        //                        $.validationEngine.isError = true;
                        promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
                    }
                }
                if (callerType == "radio" || callerType == "checkbox") {
                    callerName = $(caller).attr("name");

                    if ($("input[name='" + callerName + "']:checked").size() == 0) {
                        //                        $.validationEngine.isError = true;
                        if ($("input[name='" + callerName + "']").size() == 1) {
                            promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe + "<br />";
                        } else {
                            promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple + "<br />";
                        }
                    }
                }
                if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you		
                    if (!$(caller).val()) {
                        //                        $.validationEngine.isError = true;
                        promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
                    }
                }
                if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you	
                    if (!$(caller).find("option:selected").val()) {
                        //                        $.validationEngine.isError = true;
                        promptText += $.validationEngine.settings.allrules[rules[i]].alertText + "<br />";
                    }
                }
            }
            function _customRegex(caller, rules, position) {		 // VALIDATE REGEX RULES
                customRule = rules[position + 1];
                pattern = eval($.validationEngine.settings.allrules[customRule].regex);

                if ($(caller).attr('value') != "" && !pattern.test($(caller).attr('value'))) {
                    //                    $.validationEngine.isError = true;
                    promptText += $.validationEngine.settings.allrules[customRule].alertText + "<br />";
                }
            }
            //            function _ajax(caller, rules, position) {				 // VALIDATE AJAX RULES

            //                customAjaxRule = rules[position + 1];
            //                postfile = $.validationEngine.settings.allrules[customAjaxRule].file;
            //                fieldValue = $(caller).val();
            //                ajaxCaller = caller;
            //                fieldId = $(caller).attr("id");
            //                ajaxValidate = true;
            //                ajaxisError = $.validationEngine.isError;

            //                if (!$.validationEngine.settings.allrules[customAjaxRule].extraData) {
            //                    extraData = $.validationEngine.settings.allrules[customAjaxRule].extraData;
            //                } else {
            //                    extraData = "";
            //                }
            //                /* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */
            //                if (!ajaxisError) {
            //                    $.ajax({
            //                        type: "POST",
            //                        url: postfile,
            //                        async: true,
            //                        data: "validateValue=" + fieldValue + "&validateId=" + fieldId + "&validateError=" + customAjaxRule + extraData,
            //                        beforeSend: function() {		// BUILD A LOADING PROMPT IF LOAD TEXT EXIST		   			
            //                            if ($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad) {

            //                                if (!$("div." + fieldId + "formError")[0]) {
            //                                    return $.validationEngine.buildPrompt(ajaxCaller, $.validationEngine.settings.allrules[customAjaxRule].alertTextLoad, "load");
            //                                } else {
            //                                    $.validationEngine.updatePromptText(ajaxCaller, $.validationEngine.settings.allrules[customAjaxRule].alertTextLoad, "load");
            //                                }
            //                            }
            //                        },
            //                        error: function(data, transport) { $.validationEngine.debug("error in the ajax: " + data.status + " " + transport) },
            //                        success: function(data) {					// GET SUCCESS DATA RETURN JSON
            //                            data = eval("(" + data + ")"); 			// GET JSON DATA FROM PHP AND PARSE IT
            //                            ajaxisError = data.jsonValidateReturn[2];
            //                            customAjaxRule = data.jsonValidateReturn[1];
            //                            ajaxCaller = $("#" + data.jsonValidateReturn[0])[0];
            //                            fieldId = ajaxCaller;
            //                            ajaxErrorLength = $.validationEngine.ajaxValidArray.length;
            //                            existInarray = false;

            //                            if (ajaxisError == "false") {			// DATA FALSE UPDATE PROMPT WITH ERROR;

            //                                _checkInArray(false)				// Check if ajax validation alreay used on this field

            //                                if (!existInarray) {		 			// Add ajax error to stop submit		 		
            //                                    $.validationEngine.ajaxValidArray[ajaxErrorLength] = new Array(2);
            //                                    $.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;
            //                                    $.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;
            //                                    existInarray = false;
            //                                }

            //                                $.validationEngine.ajaxValid = false;
            //                                promptText += $.validationEngine.settings.allrules[customAjaxRule].alertText + "<br />";
            //                                $.validationEngine.updatePromptText(ajaxCaller, promptText, "", true);
            //                            } else {
            //                                _checkInArray(true);
            //                                $.validationEngine.ajaxValid = true;
            //                                if ($.validationEngine.settings.allrules[customAjaxRule].alertTextOk) {	// NO OK TEXT MEAN CLOSE PROMPT	 			
            //                                    $.validationEngine.updatePromptText(ajaxCaller, $.validationEngine.settings.allrules[customAjaxRule].alertTextOk, "pass", true);
            //                                } else {
            //                                    ajaxValidate = false;
            //                                    $.validationEngine.closePrompt(ajaxCaller);
            //                                }
            //                            }
            //                            function _checkInArray(validate) {
            //                                for (x = 0; x < ajaxErrorLength; x++) {
            //                                    if ($.validationEngine.ajaxValidArray[x][0] == fieldId) {
            //                                        $.validationEngine.ajaxValidArray[x][1] = validate;
            //                                        existInarray = true;

            //                                    }
            //                                }
            //                            }
            //                        }
            //                    });
            //                }
            //            }
            //            function _confirm(caller, rules, position) {		 // VALIDATE FIELD MATCH
            //                confirmField = rules[position + 1];

            //                if ($(caller).attr('value') != $("#" + confirmField).attr('value')) {
            //                    $.validationEngine.isError = true;
            //                    promptText += $.validationEngine.settings.allrules["confirm"].alertText + "<br />";
            //                }
            //            }
            function _length(caller, rules, position) {    	  // VALIDATE LENGTH

                startLength = eval(rules[position + 1]);
                endLength = eval(rules[position + 2]);
                feildLength = $(caller).attr('value').length;

                if (feildLength < startLength || feildLength > endLength) {
                    //                    $.validationEngine.isError = true;
                    promptText += $.validationEngine.settings.allrules["length"].alertText + startLength + $.validationEngine.settings.allrules["length"].alertText2 + endLength + $.validationEngine.settings.allrules["length"].alertText3 + "<br />"
                }
            }
            //            function _maxCheckbox(caller, rules, position) {  	  // VALIDATE CHECKBOX NUMBER

            //                nbCheck = eval(rules[position + 1]);
            //                groupname = $(caller).attr("name");
            //                groupSize = $("input[name='" + groupname + "']:checked").size();
            //                if (groupSize > nbCheck) {
            //                    $.validationEngine.showTriangle = false;
            //                    $.validationEngine.isError = true;
            //                    promptText += $.validationEngine.settings.allrules["maxCheckbox"].alertText + "<br />";
            //                }
            //            }
            //            function _minCheckbox(caller, rules, position) {  	  // VALIDATE CHECKBOX NUMBER

            //                nbCheck = eval(rules[position + 1]);
            //                groupname = $(caller).attr("name");
            //                groupSize = $("input[name='" + groupname + "']:checked").size();
            //                if (groupSize < nbCheck) {

            //                    $.validationEngine.isError = true;
            //                    $.validationEngine.showTriangle = false;
            //                    promptText += $.validationEngine.settings.allrules["minCheckbox"].alertText + " " + nbCheck + " " + $.validationEngine.settings.allrules["minCheckbox"].alertText2 + "<br />";
            //                }
            //            }
            //            if (promptText) {
            //                $.validationEngine.ArrError[$(caller).attr("id")] = promptText;
            //            }
            return promptText; //($.validationEngine.isError) ? $.validationEngine.isError : false;
        },
        //        submitForm: function(caller) {
        //            if ($.validationEngine.settings.ajaxSubmit) {
        //                if ($.validationEngine.settings.ajaxSubmitExtraData) {
        //                    extraData = $.validationEngine.settings.ajaxSubmitExtraData;
        //                } else {
        //                    extraData = "";
        //                }
        //                $.ajax({
        //                    type: "POST",
        //                    url: $.validationEngine.settings.ajaxSubmitFile,
        //                    async: true,
        //                    data: $(caller).serialize() + "&" + extraData,
        //                    error: function(data, transport) { $.validationEngine.debug("error in the ajax: " + data.status + " " + transport) },
        //                    success: function(data) {
        //                        if (data == "true") {			// EVERYTING IS FINE, SHOW SUCCESS MESSAGE
        //                            $(caller).css("opacity", 1)
        //                            $(caller).animate({ opacity: 0, height: 0 }, function() {
        //                                $(caller).css("display", "none");
        //                                $(caller).before("<div class='ajaxSubmit'>" + $.validationEngine.settings.ajaxSubmitMessage + "</div>");
        //                                $.validationEngine.closePrompt(".formError", true);
        //                                $(".ajaxSubmit").show("slow");
        //                                if ($.validationEngine.settings.success) {	// AJAX SUCCESS, STOP THE LOCATION UPDATE
        //                                    $.validationEngine.settings.success && $.validationEngine.settings.success();
        //                                    return false;
        //                                }
        //                            })
        //                        } else {						// HOUSTON WE GOT A PROBLEM (SOMETING IS NOT VALIDATING)
        //                            data = eval("(" + data + ")");
        //                            if (!data.jsonValidateReturn) {
        //                                $.validationEngine.debug("you are not going into the success fonction and jsonValidateReturn return nothing");
        //                            }
        //                            errorNumber = data.jsonValidateReturn.length
        //                            for (index = 0; index < errorNumber; index++) {
        //                                fieldId = data.jsonValidateReturn[index][0];
        //                                promptError = data.jsonValidateReturn[index][1];
        //                                type = data.jsonValidateReturn[index][2];
        //                                $.validationEngine.buildPrompt(fieldId, promptError, type);
        //                            }
        //                        }
        //                    }
        //                })
        //                return true;
        //            }
        //            if ($.validationEngine.settings.success) {	// AJAX SUCCESS, STOP THE LOCATION UPDATE
        //                if ($.validationEngine.settings.unbindEngine) { $(caller).unbind("submit") }
        //                $.validationEngine.settings.success && $.validationEngine.settings.success();
        //                return true;
        //            }
        //            return false;
        //        },
        buildPrompt: function(caller, promptText, type, ajaxed) {			// ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
            if (!$.validationEngine.settings) {
                $.validationEngine.defaultSetting()
            }
            var divFormError = document.createElement('div');
            var formErrorContent = document.createElement('div');

            linkTofield = $.validationEngine.linkTofield(caller)
            $(divFormError).addClass("formError")

            if (type == "pass") { $(divFormError).addClass("greenPopup") }
            if (type == "load") { $(divFormError).addClass("blackPopup") }
            if (ajaxed) { $(divFormError).addClass("ajaxed") }

            $(divFormError).addClass(linkTofield);
            $(formErrorContent).addClass("formErrorContent");

            $("body").append(divFormError);
            $(divFormError).append(formErrorContent);

            if ($.validationEngine.showTriangle != false) {		// NO TRIANGLE ON MAX CHECKBOX AND RADIO
                var arrow = document.createElement('div');
                $(arrow).addClass("formErrorArrow");
                $(divFormError).append(arrow);
                if ($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight") {
                    $(arrow).addClass("formErrorArrowBottom")
                    $(arrow).empty().html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
                }
                if ($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight") {
                    $(divFormError).append(arrow);
                    $(arrow).empty().html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
                }
            }
            $(formErrorContent).empty().html(promptText)

            callerTopPosition = $(caller).offset().top;
            callerleftPosition = $(caller).offset().left;
            callerWidth = $(caller).width();
            inputHeight = $(divFormError).height();

            /* POSITIONNING */
            if ($.validationEngine.settings.promptPosition == "topRight") { callerleftPosition += callerWidth - 45; callerTopPosition += -inputHeight - 3; }
            if ($.validationEngine.settings.promptPosition == "topLeft") { callerTopPosition += -inputHeight - 10; }

            if ($.validationEngine.settings.promptPosition == "centerRight") { callerleftPosition += callerWidth + 13; }

            if ($.validationEngine.settings.promptPosition == "bottomLeft") {
                callerHeight = $(caller).height();
                callerleftPosition = callerleftPosition;
                callerTopPosition = callerTopPosition + callerHeight + 15;
            }
            if ($.validationEngine.settings.promptPosition == "bottomRight") {
                callerHeight = $(caller).height();
                callerleftPosition += callerWidth - 30;
                callerTopPosition += callerHeight + 15;
            }
            $(divFormError).css({
                top: callerTopPosition,
                left: callerleftPosition,
                opacity: 0
            })
            $(caller).addClass("formErrorCall");
            setTimeout("$('.formError').click();", 3000);
            //            $(".formError").live("click", function() {	 // REMOVE BOX ON CLICK
            //                $(this).fadeOut(150, function() { $(this).remove() });
            //            })

            return $(divFormError).css("z-index", parseInt(new Date().getTime() / 1000 + 310)).animate({ "opacity": 0.77 }, function() { return true; });
        },
        updatePromptText: function(caller, promptText, type, ajaxed) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED

            linkTofield = $.validationEngine.linkTofield(caller);
            var updateThisPrompt = "." + linkTofield;

            if (type == "pass") { $(updateThisPrompt).addClass("greenPopup") } else { $(updateThisPrompt).removeClass("greenPopup") };
            if (type == "load") { $(updateThisPrompt).addClass("blackPopup") } else { $(updateThisPrompt).removeClass("blackPopup") };
            if (ajaxed) { $(updateThisPrompt).addClass("ajaxed") } else { $(updateThisPrompt).removeClass("ajaxed") };

            $(updateThisPrompt).find(".formErrorContent").empty().html(promptText);
            callerTopPosition = $(caller).offset().top;
            inputHeight = $(updateThisPrompt).height();

            if ($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight") {
                callerHeight = $(caller).height();
                callerTopPosition = callerTopPosition + callerHeight + 15;
            }
            if ($.validationEngine.settings.promptPosition == "centerRight") { callerleftPosition += callerWidth + 13; }
            if ($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight") {
                callerTopPosition = callerTopPosition - inputHeight - 10;
            }
            $(updateThisPrompt).animate({ top: callerTopPosition });
        },
        linkTofield: function(caller) {
            linkTofield = $(caller).attr("id") + "formError";
            linkTofield = linkTofield.replace(/\[/g, "");
            linkTofield = linkTofield.replace(/\]/g, "");
            return linkTofield;
        },
        closePrompt: function(caller, outside) {						// CLOSE PROMPT WHEN ERROR CORRECTED
            if (!$.validationEngine.settings) {
                $.validationEngine.defaultSetting()
            }
            $(caller).removeClass("formErrorCall");
            if (outside) {
                $(caller).fadeTo("fast", 0, function() {
                    $(caller).remove();
                });
                return false;
            }
            //            if (!ajaxValidate) {
            //                linkTofield = $.validationEngine.linkTofield(caller);
            //                closingPrompt = "." + linkTofield;
            //                $(closingPrompt).fadeTo("fast", 0, function() {
            //                    $(closingPrompt).remove();
            //                });
            //            }
        },
        debug: function(error) {
            if (!$("#debugMode")[0]) {
                $("body").append("<div id='debugMode'><div class='debugError'><strong>This is a debug mode, you got a problem with your form, it will try to help you, refresh when you think you nailed down the problem</strong></div></div>");
            }
            $(".debugError").append("<div class='debugerror'>" + error + "</div>");
        },
        submitValidation: function(caller, settings) {					// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
            //                    var fname = this.fname || regetem;
            var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
            var ptem123321 = $(caller);
            var sErrMsg = '';
            if (ptem123321.size() <= 0) { return sErrMsg; }
            if (sErrMsg == '') {
                ptem123321.find(" input[type='text'][id^='txt'][class*=validate]").each(function() {
                    var regetem = this.id.match(regexp1);
                    if (regetem != null) {
                        sErrMsg = $.validationEngine.loadValidation(this, caller); if (sErrMsg) { sErrMsg = (this.fname || regetem[0]) + sErrMsg; return false; }
                    }
                });
            }
            if (sErrMsg == '') {
                ptem123321.find(" input[type='text'][id^='jlu'][class*=validate]").each(function() {
                    var regetem = this.id.match(regexp1);
                    if (regetem != null) {
                        sErrMsg = $.validationEngine.loadValidation(this, caller); if (sErrMsg) { sErrMsg = (this.fname || regetem[0]) + sErrMsg; return false; }
                    }
                });
            }
            if (sErrMsg == '') {
                ptem123321.find(" textarea[id^='txt'][class*=validate]").each(function() {
                    var regetem = this.id.match(regexp1);
                    if (regetem != null) {
                        sErrMsg = $.validationEngine.loadValidation(this, caller); if (sErrMsg) { sErrMsg = (this.fname || regetem[0]) + sErrMsg; return false; }
                    }
                });
            }
            if (sErrMsg == '') {
                ptem123321.find(" select[id^='dpl'][class*=validate]").each(function() {
                    var regetem = this.id.match(regexp1);
                    if (regetem != null) {
                        sErrMsg = $.validationEngine.loadValidation(this, caller); if (sErrMsg) { sErrMsg = (this.fname || regetem[0]) + sErrMsg; return false; }
                    }
                });
            }
            if (sErrMsg) { alert( sErrMsg); }
            return sErrMsg;

            //            
            //            
            //            
            //            
            //            var stopForm = false;
            //            $.validationEngine.ArrError = {};
            //            $.validationEngine.ajaxValid = true;
            //            $(caller).find(".formError").remove();
            //            var toValidateSize = $(caller).find("[class*=validate]").size();

            //            $(caller).find("[class*=validate]").each(function() {
            //                linkTofield = $.validationEngine.linkTofield(this);

            //                if (!$("." + linkTofield).hasClass("ajaxed")) {	// DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry)
            //                    var validationPass = $.validationEngine.loadValidation(this, caller);
            //                    return (validationPass) ? stopForm = true : "";
            //                };
            //            });
            //            ajaxErrorLength = $.validationEngine.ajaxValidArray.length; 	// LOOK IF SOME AJAX IS NOT VALIDATE
            //            for (x = 0; x < ajaxErrorLength; x++) {
            //                if ($.validationEngine.ajaxValidArray[x][1] == false) {
            //                    $.validationEngine.ajaxValid = false;
            //                }
            //            }
            //            if (stopForm || !$.validationEngine.ajaxValid) {		// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
            //                if ($.validationEngine.settings.animateSubmit) {
            //                    destination = $(".formError:not('.greenPopup'):first").offset().top;
            //                    $(".formError:not('.greenPopup')").each(function() {
            //                        testDestination = $(this).offset().top;
            //                        if (destination > testDestination) {
            //                            destination = $(this).offset().top;
            //                        }
            //                    })
            //                    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1100);
            //                }

            //                for (m in $.validationEngine.ArrError) {
            //                    $("#" + m).focus();
            //                    break;
            //                }
            //                return true;
            //            } else {
            //                return false;
            //            }
        }
    }
})(jQuery);
$(window).load(function() {
    $("form").validationEngine();
});


//form
//IE FIRFOX
window.onbeforeunload = function (oEvent) { 
    //    oEvent = oEvent || window.event; ClearSession();
    //    var n = window.event.screenX - window.screenLeft;
    //    var b = document.documentElement && n > document.documentElement.scrollWidth - 20;
    //    return b;
    //    if (b && window.event.clientY < 0 || window.event.altKey) {
//    if (!window.event.clientY || window.event.clientY < 0 || window.event.altKey) {
        if (!hasdocloseeven) { if (sPageEditMode != null && (sPageEditMode == "EDIT" || sPageEditMode == "ADD")) { return "\u8BE5\u9875\u9762\u6B63\u5904\u4E8E\u7F16\u8F91\u6216\u65B0\u589E\u72B6\u6001\uFF0C\u672A\u4FDD\u5B58\uFF0C\u662F\u5426\u8981\u7EE7\u7EED\u5173\u95ED\uFF1F"; } }
//    }
};
function doClearDomHtml(_dDom) {
    var it1 = _dDom.childNodes.length;
    if (it1 == 0) {
        var it2 = _dDom.length;
        for (var i = 0; i < it2; i++) {
            if (typeof (_dDom[i]) == "function") {
                _dDom[i] = null;
            }
        }
        try { _dDom.innerHTML = ""; } catch (err) { }
        try { _dDom.length = 0; } catch (err) { }
    } else {
        for (var i = 0; i < it1; i++) {
            doClearDomHtml(_dDom.childNodes[i]);
        }
    }
};
window.onunload = function () {
    $(document).focus();// ClearSession();
    try {
        for (var i = 0; i < window.frames.length; i++) {
            if (window.frames[i] && window.frames[i].frameElement) {
                window.frames[i].src = 'about:blank';
                window.frames[i] = null;
                //            window.frames[i].frameElement.document.write('');
                //            window.frames[i].frameElement.document.close();
            }
        } 
    } catch (e) {
    }
    //    doClearDomHtml(document.body);
    var it1 = window.length;
    for (var i = 0; i < it1; i++) {
        if (typeof (window[i]) == "function" || typeof (window[i]) == "var") {
            window[i] = null;
        }
    }


    //    window.opener = null;
    //    odoJsByTimeOut = null;
    //    hasdocloseeven = null;
    //    FULL = null;
    //    arrlhdDig = null;
    //    $DomMaskdiv = null;
    //    if (typeof (window["myGrid1"]) != "undefined") {
    //        window["myGrid1"] = null;
    //    }
    //    if (typeof (window["myGrid2"]) != "undefined") {
    //        window["myGrid2"] = null;
    //    }
    //    if (typeof (window["myGrid3"]) != "undefined") {
    //        window["myGrid3"] = null;
    //    }
    //    if (typeof (window["myGrid4"]) != "undefined") {
    //        window["myGrid4"] = null;
    //    }
    //    if (typeof (window["myGrid5"]) != "undefined") {
    //        window["myGrid5"] = null;
    //    }
    //    if (typeof (window["gridOption1"]) != "undefined") {
    //        window["gridOption1"] = null;
    //    }
    //    if (typeof (window["gridOption2"]) != "undefined") {
    //        window["gridOption2"] = null;
    //    }
    //    if (typeof (window["gridOption3"]) != "undefined") {
    //        window["gridOption3"] = null;
    //    }
    //    if (typeof (window["gridOption4"]) != "undefined") {
    //        window["gridOption4"] = null;
    //    }
    //    if (typeof (window["gridOption5"]) != "undefined") {
    //        window["gridOption5"] = null;
    //    }
    //    if (typeof (window["jlueditor1"]) != "undefined") {
    //        window["jlueditor1"] = null;
    //    }
    //    if (typeof (window["jlueditor2"]) != "undefined") {
    //        window["jlueditor2"] = null;
    //    }
    //    if (typeof (window["jlueditor3"]) != "undefined") {
    //        window["jlueditor3"] = null;
    //    }
    //    if (typeof (window["jlueditor4"]) != "undefined") {
    //        window["jlueditor4"] = null;
    //    }
    //    if (typeof (window["jlueditor5"]) != "undefined") {
    //        window["jlueditor5"] = null;
    //    }
    //    if (typeof (window["jlueditor6"]) != "undefined") {
    //        window["jlueditor6"] = null;
    //    }
    //    if (typeof (window["jlueditor7"]) != "undefined") {
    //        window["jlueditor7"] = null;
    //    }
    //    $(document).remove();
    //    $(document)[0] = null;
    //    document.write('');
    //    document.close();
    if (typeof (CollectGarbage) != "undefined") CollectGarbage();
};
function ClearSession() {
//    if ($("#sRadom").length > 0) {
//        $.ajax({
//            type: "POST",
//            mode: "sync",
//            // limit abortion to this input abort
//            port: "ClearSession1",
//            url: shUrlBase + "UserControl/SetClientInfo.aspx?RSESSION=" + $("#sRadom").val()
//        });
//    }
};
function dtparseString(strDtime, _iVal, _sType) {
    try {
        var arys1 = strDtime.split(' ');
        var arys2 = arys1[0].split('-');
        var arys3 = arys1[1].split(':');
        if (_iVal && _sType) {
            if (_sType == 'y') { arys2[0] = parseInt(arys2[0]) + _iVal; }
            else if (_sType == 'M') { arys2[1] = parseInt(arys2[1], 10) + _iVal; }
            else if (_sType == 'd') { arys2[2] = parseInt(arys2[2], 10) + _iVal; }
            else if (_sType == 'H') { arys3[0] = parseInt(arys3[0], 10) + _iVal; }
            else if (_sType == 'm') { arys3[1] = parseInt(arys3[1], 10) + _iVal; }
            else if (_sType == 's') { arys3[2] = parseInt(arys3[2], 10) + _iVal; }
        }
        var EndTime = new Date(arys2[0], --arys2[1], arys2[2], arys3[0], arys3[1], arys3[2]);
        return EndTime;
    } catch (e) {
        return null;
    }
};
function currentDateToString(myDate) {
    try {
        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var date = myDate.getDate();
        var hours = myDate.getHours();
        var minutes = myDate.getMinutes();
        var seconds = myDate.getSeconds();

        var myArray = Array();
        myArray[0] = year;
        myArray[1] = month > 9 ? month.toString() : '0' + month;
        myArray[2] = date > 9 ? date.toString() : '0' + date;
        myArray[3] = hours > 9 ? hours.toString() : '0' + hours;
        myArray[4] = minutes > 9 ? minutes.toString() : '0' + minutes;
        myArray[5] = seconds > 9 ? seconds.toString() : '0' + seconds;

        return myArray[0] + "-" + myArray[1] + "-" + myArray[2] + " " + myArray[3] + ":" + myArray[4] + ":" + myArray[5];
    } catch (e) {
        return "";
    }
};
var odoJsByTimeOut = [];
function doJsByTimeOut(sTimerLabel, _sCondition, _sJstem, _iSecond) {
    if (!sTimerLabel || !_sCondition || !_sJstem) return; if (!_iSecond) _iSecond = 1;
    if (odoJsByTimeOut[sTimerLabel] != null && odoJsByTimeOut[sTimerLabel].time1 != null) { window.clearInterval(odoJsByTimeOut[sTimerLabel].time1); odoJsByTimeOut[sTimerLabel].time1 = null; }
    odoJsByTimeOut[sTimerLabel] = new Object();
    odoJsByTimeOut[sTimerLabel].iSecond = _iSecond;
    odoJsByTimeOut[sTimerLabel].sJstem = _sJstem;
    odoJsByTimeOut[sTimerLabel].sCondition = _sCondition;
    var time1 = window.setInterval('doIntervalGtExecActionCmp("' + sTimerLabel + '");', 200);
    odoJsByTimeOut[sTimerLabel].time1 = time1;
};
function doIntervalGtExecActionCmp(sTimerLabel) {
    if (!odoJsByTimeOut[sTimerLabel] || !odoJsByTimeOut[sTimerLabel].iCurrTime) { odoJsByTimeOut[sTimerLabel].iCurrTime = 0; }
    odoJsByTimeOut[sTimerLabel].iCurrTime = odoJsByTimeOut[sTimerLabel].iCurrTime + 1;
    if ((odoJsByTimeOut[sTimerLabel].iCurrTime * 200) % (odoJsByTimeOut[sTimerLabel].iSecond * 1000) == 0) {
        if (eval(odoJsByTimeOut[sTimerLabel].sCondition)) {
            window.clearInterval(odoJsByTimeOut[sTimerLabel].time1); odoJsByTimeOut[sTimerLabel].time1 = null;
            eval(odoJsByTimeOut[sTimerLabel].sJstem);
        }
    }
    if (odoJsByTimeOut[sTimerLabel].iCurrTime * 200 / 1000 >= 120) {
        window.clearInterval(odoJsByTimeOut[sTimerLabel].time1); odoJsByTimeOut[sTimerLabel].time1 = null;
        alert("\u7A0B\u5E8F\u6267\u884C\u8D85\u65F6\uFF01");
    }
};
function GetPageClass() {
    var regexp1 = new RegExp("wf[A-Z|a-z|0-9|_]{3,}.[a|A][s|S][p|P][x|X]");
    var regetem = window.location.pathname.match(regexp1);
    if (regetem != null && regetem.length > 0) { return regetem[0].split('.')[0]; } return "";
};
function GetRadom(iLen) {
    var winname = (Math.random() * 100000000000).toString(); if (typeof (iLen) == "number") winname = winname.substr(0, iLen); return winname; //new Date().getTime();
};
var hasdocloseeven = false;
function onwClose(blGetMsg) { 
    hasdocloseeven = true; if (sPageEditMode != null && (sPageEditMode == "EDIT" || sPageEditMode == "ADD")) { if (!confirm("\u8BE5\u9875\u9762\u6B63\u5904\u4E8E\u7F16\u8F91\u6216\u65B0\u589E\u72B6\u6001\uFF0C\u672A\u4FDD\u5B58\uFF0C\u662F\u5426\u8981\u7EE7\u7EED\u5173\u95ED\uFF1F")) return false; }
};
function downfbyvp(svp, docid,sfnme) {
    var surltem222 = ''; if (sfnme == null) { sfnme = ''; } //sfnme = encodeURIComponent(sfnme);
    if (svp != null && svp != "") {
        surltem222 = shUrlBase + "filedown.axd?FILE_DOWNL=1&file=" + svp + "&FSNME=" + sfnme; // shUrlBase + "UserControl/FDown.aspx?FILE_DOWNL=1&file=" + svp + "&FSNME=" + sfnme;
    } else if (docid != null && docid != "") { surltem222 = shUrlBase + "filedown.axd?FILE_DOWNL=1&FILE_ID=" + docid + "&FSNME=" + sfnme; }
//    if ($.browser.msie) {
//        ShowChildForm(null, surltem222);
//    } else {
        var $iframtem = $('#ifrBlFDown'); var iframtem;
        if ($iframtem.length <= 0) {
            iframtem = $("<iframe id=\"ifrBlFDown\" width=\"1\" frameborder=\"0\" height=\"1\"></iframe>")[0];
            $("body").append(iframtem);
        } else {
            iframtem = $iframtem[0];
        }
        iframtem.contentWindow.document.write('');
        iframtem.contentWindow.document.close();
        iframtem.src = surltem222;
//    }
};
function GetDownHtml(sVPath, aText, aTip) {
    return "<img src=\"" + shUrlBase + "images/attach.png\" align=\"absmiddle\" />  " + "<a href=\"javascript:void(0);return false;\" onclick=\"downfbyvp('" + encodeURI(sVPath) + "');return false;\"  title=\"" + aTip + "\">" + aText + "</a>";
};
var screen_ht = screen.availHeight; var screen_wd = screen.availWidth; var screen_left = 0; var screen_top = 10; FULL = "left=0,top=0,directories=no,location =no,menubar =no,resizable=yes,titlebar=no,toolbar=no,scrollbars=yes,channelmode,"
function ShowChildForm(winname, url, winsize, winparms) {

    //    var urlpostf = $("#EmailForm");
    //    if (urlpostf.size() <= 0) {
    //        urlpostf = $('<a href ="' + url + '" target="_blank" onclick="alert(\'d\');" id="EmailForm">打开新选项卡</a>');
    //        urlpostf.appendTo('body');
    //    }
    //    urlpostf.attr('href', url);
    //    urlpostf.triggerHandler('click');
    //    return;
    //    urlpostf[0].submit();

    //    var urlpostf = $("#EmailForm");
    //    if (urlpostf.size() <= 0) {
    //        urlpostf = $('<form id="EmailForm" action="目标页" method="get" target="_blank"><input id="emailid" name="emailid"  type="hidden" />//隐藏域，用来放需要传递的参数</form>');
    //        urlpostf.appendTo('body');
    //    }
    //    urlpostf.html('');
    //    urlpostf.attr('action', shUrlBase + "Fws/EIB/wfFwsCsEIbSpmtEditor.aspx?MODE=VIEW&ID=" + sid);
    //    urlpostf[0].submit();
    //    window.open(url, '_blank');
    //return;
    if (winparms == null || winparms == '') winparms = FULL;
//    if (winname == null || winname == '') 
    winname = GetRadom(8);
    if (winsize == null || winsize == '') winsize = "X";
    if (winsize == "S") scalar = 0.33; else if (winsize == "M") scalar = 0.50; else if (winsize == "L") scalar = 0.75; else { winparms += "channelmode,"; scalar = 0.9; } w_ht = Math.round(scalar * screen_ht); w_wd = screen_wd; left = 0; winparms += "left=" + left + ",top=" + screen_top + ",screenX=" + left + ",screenY=" + screen_top + ","; winparms += "height=" + w_ht + ",width=" + w_wd; //if (window.noncsWin) { if (!noncsWin.closed) noncsWin.close(); }
    var noncsWin = window.open(url, winname, winparms, true);if (noncsWin) { noncsWin.focus(); } // if (noncsWin) { noncsWin.opener = null; noncsWin.focus(); } return;
};
function popupExit(langVersion, url) {
    var top = Math.round((screen_ht - 300) * 0.5); var left = Math.round((screen_wd - 460) * 0.5); var winparms = "width=460,height=200,"; winparms += "left=" + left + ",top=" + top; var windowURL = serverurl.substring(0, serverurl.length - 10) + langVersion + '/' + EXITURL; exitWin = window.open(windowURL, 'popup', winparms)
    ShowChildForm("X", url, "noncs", FULL);if (exitWin) { exitWin.focus(); }
};
function GetALink(sName, sUrl, winname, sScrip) {
    if (winname == null) winname = '';
    if (sUrl && sUrl != null)
        return "<a href=\"javascript:void(0);return false;\" onclick=\"ShowChildForm('" + winname + "','" + sUrl + "');return false;\" >" + sName + "</a>";
    else if (sScrip)
        return "<a href=\"javascript:void(0);return false;\" onclick=\" eval(unescape('" + escape(sScrip) + "'));return false;\" >" + sName + "</a>";
};
function GetALinkp(sId, sName, sUrl, oParams) {
    var _sParams = "";
    for (_sKey in oParams) {
        _sParams += "," + _sKey + ":'" + oParams[_sKey] + "'";
    }
    var sScrip = "pShowDlg('" + sId + "',{page:'" + encodeURI(sUrl) + "'" + _sParams + "});";
    return "<a href=\"javascript:void(0)\" onclick=\" eval(unescape('" + escape(sScrip) + "'));return false;\" >" + sName + "</a>";
};
function GetLinkl(sName, page) {
    return '<a href="javascript:void(0);" onclick="location.href =\'' + encodeURI(page) + '\';return false;">' + sName + '</a>';
};
function ToLogin() {
    window.top.location.href = shUrlBase + "SysLogon/" + window.location.href;
};
//function ShowSpmtHeaderLinkEob(sId, sBkno, sSt) {
//    var arrPage = [{ name: '委托', page: 'Fws/EOB/wfFwsCsEObSpmtEditor.aspx?ID=' }
//    , { name: '报关', page: 'Fws/EOB/wfFwsCsEObManifestJobEditor.aspx?ID=' }
//    , { name: '单证', page: 'Fws/EOB/wfFwsCsEObBlDocumentTxtEditor.aspx?ID=' }
//    , { name: '计划', page: 'Fws/EOB/wfFwsCsEObServicePlanList.aspx?ID=' }
//    , { name: '订舱', page: 'Fws/EOB/wfFwsOsEObSpmtSeaBookingEditor.aspx?ID=' }
//    , { name: '现场', page: 'Fws/EOB/wfFwsCsEObPortRelIncCntrEditor.aspx?ID=' }
//    , { name: '拖车', page: 'Fws/EOB/wfFwsCsEObLandLogiJobEditor.aspx?ID=' }
//    //    , { name: '装箱', page: 'Fws/EOB/wfFwsCsEObSpmtContnrList.aspx?ID=' }
//    , { name: '支线', page: 'Fws/EOB/wfFwsOsEObSpmtFeederVslEditor.aspx?ID=' }
//    , { name: '中转', page: 'Fws/EOB/wfFwsCsEObBlDocumentTxtEditor.aspx?ID=' }
//    , { name: '干线', page: 'Fws/EOB/wfFwsOsEObSpmtSeaVslEditor.aspx?ID=' }
//    , { name: '拆并', page: 'Fws/EOB/wfFwsCsEObSpmtSplitCombList.aspx?ID=' }
//    , { name: '跟踪', page: 'Fws/EOB/wfFwsCsEObSpmtTransptLineEditor.aspx?ID='}];
//    var sHtml = '', spagenametem1 = '', spageurltem1 = '';
//    var pclasstem1 = GetPageClass();
//    for (var i = 0; i < arrPage.length; i++) {
//        var slinktem2211 = GetLinkl(arrPage[i].name, shUrlBase + arrPage[i].page + sId);
//        if (arrPage[i].page.indexOf(pclasstem1) != -1) { spagenametem1 = arrPage[i].name; spageurltem1 = arrPage[i].page; continue; }
//        sHtml += (sHtml != '' ? ' | ' : ' ') + slinktem2211;
//    }
//    sHtml = "<div id=\"spmt_header\"><div class=\"sm_l\"></div> <div id=\"spmt_finder\">       <input name=\"jlutxtPageSpmtFinderNo\" type=\"text\" width=\"70px\" maxlength=\"20\" id=\"jlutxtPageSpmtFinderNo\"  /> <a href=\"javascript:void(0);\" onclick=\"dojlutxtPageSpmtFinderNo('" + encodeURI(spageurltem1) + "');return false;\">Finder</a></div> <div id=\"divMoreBtn\"><a href=\"javascript:void(0);\" onclick=\"return false;\">" + spagenametem1 + "</a></div>     <div id=\"spmt_statustxt\"> &gt;&gt; <span class=\"no\"> " + sBkno + " </span> &gt;&gt; <span class=\"no\"> " + sSt + " </span> &gt;&gt; </div><div> " + sHtml + " </div>    <div class=\"sm_r\"></div>  </div>";
//    $("#divShowSpmtHeaderLink").empty().html(sHtml);
//    jqLookup("jlutxtPageSpmtFinderNo", "CN0011", { extraParams: { isEob: '1' }, width: 280, R_F_T: 'BK_NO', R_F_V: 'SPMT_BASIC_ID' });
//};
//function ShowSpmtHeaderLinkEib(sId, sBkno, sSt) {
//    var arrPage = [{ name: '委托', page: 'Fws/EIB/wfFwsCsEibSpmtEditor.aspx?ID=' }
//    , { name: '报关', page: 'Fws/EIB/wfFwsCsEIbManifestJobEditor.aspx?ID=' }
//    , { name: '单证', page: 'Fws/EOB/wfFwsCsEObBlDocumentTxtEditor.aspx?ID=' }
//    , { name: '计划', page: 'Fws/EOB/wfFwsCsEObServicePlanList.aspx?ID=' }
//    , { name: '订舱', page: 'Fws/EIB/wfFwsOsEIbSpmtSeaBookingEditor.aspx?ID=' }
//    , { name: '现场', page: 'Fws/EIB/wfFwsCsEIbPortCntrWorkEditor.aspx?ID=' }
//    , { name: '拖车', page: 'Fws/EIB/wfFwsCsEIbLandLogiJobEditor.aspx?ID=' }
//    //    , { name: '装箱', page: 'Fws/EOB/wfFwsCsEObSpmtContnrList.aspx?ID=' }
//    , { name: '支线', page: 'Fws/EOB/wfFwsOsEObSpmtFeederVslEditor.aspx?ID=' }
//    , { name: '中转', page: 'Fws/EIB/wfFwsCsEIbSpmtTsTracingEditor.aspx?ID=' }
//    , { name: '干线', page: 'Fws/EIB/wfFwsOsEIbSpmtSeaVslEditor.aspx?ID=' }
//    , { name: '拆并', page: 'Fws/EOB/wfFwsCsEObSpmtSplitCombList.aspx?ID=' }
//    , { name: '跟踪', page: 'Fws/EOB/wfFwsCsEObSpmtTransptLineEditor.aspx?ID='}];
//    var sHtml = '', spagenametem1 = '', spageurltem1 = '';
//    var pclasstem1 = GetPageClass();
//    for (var i = 0; i < arrPage.length; i++) {
//        var slinktem2211 = GetLinkl(arrPage[i].name, shUrlBase + arrPage[i].page + sId);
//        if (arrPage[i].page.indexOf(pclasstem1) != -1) { spagenametem1 = arrPage[i].name; spageurltem1 = arrPage[i].page; }
//        sHtml += (sHtml != '' ? ' | ' : ' ') + slinktem2211;
//    }
//    sHtml = "<div id=\"spmt_header\"><div class=\"sm_l\"></div> <div id=\"spmt_finder\">       <input name=\"jlutxtPageSpmtFinderNo\" type=\"text\" width=\"70px\" maxlength=\"20\" id=\"jlutxtPageSpmtFinderNo\"  /> <a href=\"javascript:void(0);\" onclick=\"dojlutxtPageSpmtFinderNo('" + encodeURI(spageurltem1) + "');return false;\">Finder</a></div> <div id=\"divMoreBtn\"><a href=\"javascript:void(0);\" onclick=\"return false;\">" + spagenametem1 + "</a></div>     <div id=\"spmt_statustxt\"> &gt;&gt; <span class=\"no\"> " + sBkno + " </span> &gt;&gt; <span class=\"no\"> " + sSt + " </span> &gt;&gt; </div><div> " + sHtml + " </div>    <div class=\"sm_r\"></div>  </div>";
//    $("#divShowSpmtHeaderLink").empty().html(sHtml);
//    jqLookup("jlutxtPageSpmtFinderNo", "CN0011", { extraParams: { isEib: '1' }, width: 280, R_F_T: 'BK_NO', R_F_V: 'SPMT_BASIC_ID' });
//};
function dojlutxtPageSpmtFinderNo() {
    var idtem1 = $("#jlutxtPageSpmtFinderNo").attr('combValue');
    if (!idtem1) { alert('请先输入订舱编号！'); return; }
    var isurltem = window.location.href.indexOf('ID=');
    if (isurltem > 0) {
        window.location.reload(true).substring(0,isurltem+3)  + idtem1;
    }
};
function ShowBlChange(sChangeId) {
    pShowDlg("wfFwsCsEObBlChangeList1", { page: shUrlBase + "Fws/EOB/wfFwsCseObBlChangeHandler.aspx?MODE=VIEW&ID=" + sChangeId, title: "改单记录处理", onClose: 'onwfFwsCseObBlChgBeforeClose' });
};
function onwfFwsCseObBlChgBeforeClose() {
    window.location.reload(true);
};
function GetWwidth() {
    return $(document.documentElement).width();
    //    var windowWidth ;
    //    if (self.innerHeight) {
    //        windowWidth = self.innerWidth; 
    //    } else if (document.documentElement && document.documentElement.clientHeight) {
    //        windowWidth = document.documentElement.clientWidth; 
    //    } else
    //        if (document.body) {
    //        windowWidth = document.body.clientWidth;
    //    }return windowWidth;
}
function GetWheight() {
    return $(document.documentElement).height();
    //    var  windowHeight;
    //    if (self.innerHeight) { 
    //        windowHeight = self.innerHeight;
    //    } else if (document.documentElement && document.documentElement.clientHeight) { 
    //        windowHeight = document.documentElement.clientHeight;
    //    } else
    //        if (document.body) { 
    //        windowHeight = document.body.clientHeight;
    //    }return windowHeight;
};
function mouseCoords(ev) {
    ev = ev || window.event;
    if (ev == null) {
        return;
    }
    else if (ev.pageX || ev.pageY) {
        return { x: ev.pageX, y: ev.pageY };
    }
    return {
        x: ev.clientX + $(document).scrollLeft()  - document.body.clientLeft,
        y: ev.clientY + $(document).scrollTop() - document.body.clientTop
    };
};
var flickrFeedsCache = {};
function SetShowMenu(_sBtnId, _sMenuid, blLeft) {
    $('#' + _sBtnId).poshytip({
        alignY: 'bottom',
        showTimeout:100,
        content: function (updateCallback) {
            return $("<div></div>").html($('#' + _sMenuid).html()).width($('#' + _sMenuid).width());
//            var rel = $(this).attr('rel') || _sBtnId;
//            if (flickrFeedsCache[rel] && flickrFeedsCache[rel].container)
//                return flickrFeedsCache[rel].container;
//            if (!flickrFeedsCache[rel]) {
//                flickrFeedsCache[rel] = { container: null }; 
//                flickrFeedsCache[rel].container =$("<div></div>").html( $('#' + _sMenuid).html()).width($('#' + _sMenuid).width());
//                return flickrFeedsCache[rel].container.show(); 
//            } 
        }
    });
//    Tipped.create('#' + _sBtnId, $('#' + _sMenuid)[0], { skin: 'cloud', hook: 'bottomright', fadeIn: 10, fadeOut: 10, showDelay: 15, hideDelay: 25 });

    //    var $_sMenuid =typeof (_sMenuid) == "string"? $("#" + _sMenuid):$(_sMenuid);
    //    var $_sBtnId = typeof (_sBtnId) == "string" ? $("#" + _sBtnId) : $(_sBtnId);
    //    $('body').append($_sMenuid);
    //    var _timeout; 
    //    $_sMenuid.hide();
    //    $_sBtnId.hover(function() {
    //        var iLefttem1 = $_sBtnId.offset().left;
    //        var iToptem1 = $_sBtnId.offset().top + $_sBtnId.outerHeight();
    //        if (blLeft === true) {
    //            iLefttem1 = $_sBtnId.offset().left + $_sBtnId.outerWidth();
    //            iToptem1 = $_sBtnId.offset().top;
    //        }
    //        if ($(window).height() + $(document).scrollTop() < iToptem1 + $_sMenuid.outerHeight()) {
    //            iToptem1 = $_sBtnId.offset().top - $_sMenuid.outerHeight();
    //        }
    //        $_sMenuid.css("position", "absolute").css("display", "block").css("z-index", parseInt(new Date().getTime() / 100) + 210);
    //        $_sMenuid.css("left", iLefttem1).css("top", iToptem1);
    //        clearTimeout(_timeout); $_sMenuid.fadeIn("fast").show("fast");
    //    },
    //    function() {
    //        clearTimeout(_timeout); _timeout = setTimeout(function() { $("#" + _sMenuid + "").fadeOut("fast").hide("fast"); }, 300);
    //    });
    //    $_sMenuid.hover(function() {
    //        clearTimeout(_timeout); $_sMenuid.fadeIn("slow").show("fast");
    //    },
    //    function() {
    //        clearTimeout(_timeout); _timeout = setTimeout(function() { $("#" + _sMenuid + "").fadeOut("fast").hide("fast"); }, 300);
    //    });
};
function SetShowDiv(domBtn, _sMenuid, blLeft) {
    var $_sMenuid = $("#" + _sMenuid);
    var $_sBtnId = $(domBtn);
    $('body').append($_sMenuid);
    var _timeout;
    $_sMenuid.hide();
    $_sBtnId.hover(function() {
        var mousePos = mouseCoords();
        $_sMenuid.css("position", "absolute").css("display", "block").css("z-index", parseInt(new Date().getTime() / 100) + 210);
        $_sMenuid.css("left", mousePos.x).css("top", mousePos.y);
        clearTimeout(_timeout); $_sMenuid.fadeIn("fast").show("fast");
    },
    function() {
        clearTimeout(_timeout); _timeout = setTimeout(function() { $("#" + _sMenuid + "").fadeOut("fast").hide("fast"); }, 300);
    });
    $_sMenuid.hover(function() {
        clearTimeout(_timeout); $_sMenuid.fadeIn("slow").show("fast");
    },
    function() {
        clearTimeout(_timeout); _timeout = setTimeout(function() { $("#" + _sMenuid + "").fadeOut("fast").hide("fast"); }, 300);
    });
};
function OpenBox(surl, sWidth, sHeight, sTitle, arrParam) {
    $.fn.colorbox.init();
    if (arrParam != null) { if (arrParam.oOpenW == null) { arrParam.oOpenW = window; } $.fn.colorbox(arrParam); }
    else { if (sWidth == null) sWidth = "92%"; if (sHeight == null) sHeight = "92%"; if (sTitle == null) sTitle = "Title"; $.fn.colorbox({ href: surl, title: sTitle, iframe: true, overlayClose: false, width: "92%", height: "92%", oOpenW: window }); }
};
function OpenDialog(surl, sWidth, sHeight, sTitle, aParams) {
    //    if (typeof (window.parent.parent.parent.addTabPage) == 'function') {
    //        window.parent.parent.parent.addTabPage(sTitle, surl);
    //        return;
    //    }

    var sId = sTitle + "_lhd";sId = sId.substr(0, 4);
    var _oParams = $.extend({}, { page: surl, openwin: window, width: sWidth, height: sHeight, title: sTitle }, aParams);
    var dg = pShowDlg(sId, _oParams);
    return;



    //    if (!window.parent.parent.parent.parent.parent.isDislogOpenColorbox) {
    //        if (arrParam != null) { if (arrParam.oOpenW == null) { arrParam.oOpenW = window; } window.parent.parent.parent.parent.parent.$.fn.colorbox(arrParam); return; }
    //        if (sWidth == null) sWidth = window.parent.parent.parent.parent.parent.document.documentElement.offsetWidth * 0.92; if (sHeight == null) sHeight = window.parent.parent.parent.parent.parent.document.documentElement.offsetHeight * 0.92; var winname = GetRadom(8);
    //        window.parent.parent.parent.parent.parent.isDislogOpenColorbox = true;
    //        window.parent.parent.parent.parent.parent.$.fn.colorbox({ name: winname, href: surl, title: sTitle, iframe: true, overlayClose: false, width: sWidth, height: sHeight, oOpenW: window, onClosed: function() { window.parent.parent.parent.parent.parent.isDislogOpenColorbox = false; } });
    //    } else {
    //        OpenBox(surl, sWidth, sHeight, sTitle, arrParam);
    //    }
};
function CloseActiveW(_blUpdataP) {
    if (this.frameElement && $(this.frameElement).attr('tabwstitle') && this.parent.CloseTabByid) {
        this.parent.CloseTabByid($(this.frameElement).attr('tabwstitle'));
        return;
    }
    var dgtem1 = GetODG();
    if (dgtem1 != null) {
        var openW = dgtem1.getOpt('openwin');
        if (_blUpdataP && openW != null) { openW.location.href = openW.location.href; }
        dgtem1.cancel(); return;
    }
    if (window.parent.location == window.location) {
        window.opener = null;
        window.open(' ', '_self', ' ');
        window.close();
    }
    //    window.parent.parent.parent.$.fn.colorbox.close();
};
var arrlhdDig = [];
function ShowDlg(sId, aParams) {
    var _oParams = $.extend({}, { id: sId, cover: true, skin: "default", minBtn: true }, aParams);
    doShowDlg(sId, _oParams);
};
function pShowDlg(sId, aParams) {
    var _oParams = $.extend({}, { id: sId, cover: true, skin: "default", minBtn: true, openwin: window }, aParams);
    window.parent.parent.parent.parent.parent.doShowDlg(sId, _oParams);
};
function pHideDlg(sId) {
    window.parent.parent.parent.parent.parent.HideDlg(sId);
};
var $DomMaskdiv;
function ShowMask(aParams) {
    if ($DomMaskdiv == null) {
        var htmltem = "<div class=\"custmask-msg\"><div class=\"custmask-msg1\">&nbsp;" + aParams.msg + "</div><div class=\"custmask-msg2\"></div></div>";
        $DomMaskdiv = $(htmltem);
    }
    $DomMaskdiv.find(".custmask-msg1").empty().html(aParams.msg);
    var _oParams = $.extend({}, { id: "ShowMask_Dlg_id", html: $DomMaskdiv[0], width: 300, height: 98, title: "Please Waiting......", bgcolor: '#CCC', cover: true, xButton: false, skin: "default" }, aParams);
    doShowDlg("ShowMask_Dlg_id", _oParams);
};
function HideMask() {
    HideDlg("ShowMask_Dlg_id");
};
function doShowDlg(sId, aParams) {
    var dgtm;
    var sWidth = $(document.documentElement).width() - 20; var sHeight = $(document.documentElement).height() - 20;
    if (aParams.width && typeof (aParams.width) == "string" && aParams.width.indexOf('%') != -1) { aParams.width = sWidth * parseFloat(aParams.width) / 100; }
    if (aParams.height && typeof (aParams.height) == "string" && aParams.height.indexOf('%') != -1) { aParams.height = sHeight * parseFloat(aParams.height) / 100; }
    if (aParams.page) {
        aParams.page = aParams.page + (aParams.page.indexOf("?") >= 0 ? "&frmrandomt=" : "?frmrandomt=") + Math.floor(Math.random() * 100000);
    }
    var _oParams = $.extend({}, { id: sId, width: sWidth, height: sHeight, parent: window, openwin: window, title: "\u5BF9\u8BDD\u6846", bgcolor: '#999', iconTitle: false, minBtn: true, opacity: 0.8, fixed: true, rang: true, btnBar: false, cover: false, lockScroll: true }, aParams);
    _oParams.width = _oParams.width == null ? sWidth : _oParams.width;
    _oParams.height = _oParams.height == null ? sHeight : _oParams.height;
    if (arrlhdDig[sId] == null) {
        _oParams.onCancel = function() {
            try {
                var _onClose = this.getOpt('onClose');
                if (this.getOpt('page') && (this.dgWin.onwClose && this.dgWin.onwClose(this.openWin) === false)) {
                    return false;
                }
                if (_onClose && (typeof _onClose === 'string' && this.openWin[_onClose](this.dgWin) === false || typeof _onClose !== 'string' && _onClose(this.dgWin) === false)) {
                    return false;
                }
            } catch (e) {
                alert(e.message); return true;
            }
        };
        dgtm = new $.dialog(_oParams);
        dgtm.openWin = _oParams.openwin;
        arrlhdDig[sId] = dgtm;
        dgtm.ShowDialog();
    } else {
        dgtm = arrlhdDig[sId];
        dgtm.openWin = _oParams.openwin;
        dgtm.setOpt('openwin', _oParams.openwin);
        dgtm.setOpt('parent', _oParams.parent);
        dgtm.setOpt('page', _oParams.page);
        dgtm.ShowDialog();
        dgtm.reDialogSize(_oParams.width, _oParams.height);
    }
    if (_oParams.page && dgtm.dgFrm && dgtm.dgFrm.src != _oParams.page) {
        dgtm.dgFrm.contentWindow.document.write('');
        dgtm.dgFrm.contentWindow.document.close(); dgtm.dgFrm.src = _oParams.page;
    }
    return dgtm;
};
function HideDlg(sId, aParams) {
    if (arrlhdDig[sId] != null) {
        arrlhdDig[sId].cancel();
    }
};
function GetQueryString(sProp, sUrl) {
    var re = new RegExp("[&,?]" + sProp + "=([^//&]*)", "i");
    var a = re.exec(sUrl || document.location.search);
    if (a == null)
        return "";
    return a[1];
};
function GetODG() {
    var sId = window.frameElement && window.frameElement.getAttribute('lhgdgsrcid');
    if (sId && parent.arrlhdDig && parent.arrlhdDig[sId] != null) {
        return parent.arrlhdDig[sId];
    }
    return null;
};
function GetOpenW() {
    var dgtem1 = GetODG();
    if (dgtem1 != null) {
        var openW = dgtem1.openWin;
        if (openW != null) { return openW; }
    }
    return parent;
};
function PopDialog(sDivCid, sTitle, sWidth, sHeight, _cover) {
    if (sWidth == null) sWidth = $(document.documentElement).width() - 80; if (sHeight == null) sHeight = $(document.documentElement).height() - 30;
    //    var dg = new $.dialog({ id: sDivCid+"_lhd", html: 'lhgdialog' });
    var sId = sDivCid + "_lhd";
    var dg = doShowDlg(sId, { html: $('#' + sDivCid)[0], width: sWidth, height: sHeight, title: sTitle, cover: false || _cover });
    return dg;

};
function ClosePop(sDivCid) {
    var sId = sDivCid + "_lhd";
    HideDlg(sId);
    return;
    if (!sDivCid) return; var $inputDiv = $("#" + sDivCid); if ($inputDiv.length <= 0) return; if (!$inputDiv[0].PopDialogId) return; var $PopDialog = $("#" + $inputDiv[0].PopDialogId); if ($PopDialog.length > 0) { $PopDialog.hide(); }
};
function jsonRow() { this.arrjson = {}; }
jsonRow.prototype = {
    AddCell: function(sName, sValue) {
        if (!sName) return; this.arrjson[sName] = sValue;
    },
    GetStr: function() {
        var _strjson = "";
        for (m in this.arrjson) {
            if (_strjson == "") { _strjson = "\"" + m + "\":\"" + encodeURIComponent(this.arrjson[m]) + "\""; } else { _strjson += ",\"" + m + "\":\"" + encodeURIComponent(this.arrjson[m]) + "\""; }
        }
        if (_strjson == "") return ""; else return "{" + _strjson + "}";
    }
};
function strToJsons(o) {
    var i, v ;
    v = '\bb\tt\nn\ff\rr\""\'\'\\\\';

    return '' + o.replace(/([\u0080-\uFFFF\x00-\x1f\"])/g, function (a, b) {
        i = v.indexOf(b);

        if (i + 1)
            return '\\' + v.charAt(i + 1);

        a = b.charCodeAt().toString(16);

        return '\\u' + '0000'.substring(a.length) + a;
    }) + '';
};
function replaceAll(content, oldReplace, newReplace) {
    var i;
    var newReplacetem221122 = newReplace;
    newReplace = "#*@*!*@*#*!";
    for (i = 0; i < content.length; i++) {
        if (content.indexOf(oldReplace) > 0) {
            content = content.replace(oldReplace, newReplace);
        }
    }
    oldReplace = newReplace;
    newReplace = newReplacetem221122;
    for (i = 0; i < content.length; i++) {
        if (content.indexOf(oldReplace) > 0) {
            content = content.replace(oldReplace, newReplace);
        }
    }
    return content;
};
//function strToJsons(s) {
//    if (s == null || s == "") { return ""; } else if (typeof (s) != "string") { return s.toString(); }
//    var sb = ""; s = s.split('');
//    for (var i = 0; i < s.length; i++) {
//        var c = s[i];
//        switch (c) {
//            case '\"':
//                sb += "\\\"";
//                break;
//            case '\\':
//                sb += "\\\\";
//                break;
//            case '/':
//                sb += "\\/";
//                break;
//            case '\b':
//                sb += "\\b";
//                break;
//            case '\f':
//                sb += "\\f";
//                break;
//            case '\n':
//                sb += "\\n";
//                break;
//            case '\r':
//                sb += "\\r";
//                break;
//            case '\t':
//                sb += "\\t";
//                break;
//            default:
//                sb += c;
//                break;
//        }
//    }
//    return sb;
//}

function BoundCotr(pCid, jsrow) {
    if (jsrow == null || jsrow.length <= 0) return;
    var ptem123321 = $("#" + pCid);
    if (ptem123321.size() <= 0) { return; }
    var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
    ptem123321.find(" input[type='checkbox'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).attr("checked", (jsrow[regetem[0]] == "true" || jsrow[regetem[0]] == "True"));
        }
    });
    ptem123321.find(" input[type='radio'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).attr("checked", (jsrow[regetem[0]] == "true" || jsrow[regetem[0]] == "True"));
        }
    });
    ptem123321.find(" span[id]").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).empty().html(jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" input[type='text'][id^='jlu']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            var $inputctem1 = $(this);
            var scolnT = $inputctem1.attr("R_F_T") ? $inputctem1.attr("R_F_T") : regetem[0].substr(0, regetem[0].length - 3) + "NME";
            var scolnV = $inputctem1.attr("R_F_V") ? $inputctem1.attr("R_F_V") : regetem[0].substr(0, regetem[0].length - 3) + "CDE";
            if ($inputctem1.attr('sShowField') == $inputctem1.attr('sValueField') && jsrow[scolnV] != null) {
                $inputctem1.val(jsrow[scolnV]);
            }
            if ($inputctem1.attr('sShowField') == $inputctem1.attr('sTextField') && jsrow[scolnT] != null) {
                $inputctem1.val(jsrow[scolnT]);
            } else {
                $inputctem1.val(jsrow[regetem[0]]);
            }
            if (jsrow[scolnV] != null) { $inputctem1.attr('combValue', jsrow[scolnV]); } else { $inputctem1.attr('combValue', jsrow[regetem[0]]); }
            if (jsrow[scolnT] != null) { $inputctem1.attr('combText', jsrow[scolnT]); } else { $inputctem1.attr('combText', jsrow[regetem[0]]); }




            //            if (inputctem1.R_F_T && jsrow[inputctem1.R_F_T] != null) {
            //                scolnT = inputctem1.R_F_T;
            //            }
            //            if (inputctem1.R_F_V && jsrow[inputctem1.R_F_V] != null) {
            //                scolnV = inputctem1.R_F_V;
            //            }
            //            if (jsrow[scolnV] == null) scolnV = jsrow[regetem[0]]; else scolnV = jsrow[scolnV];
            //            if (jsrow[scolnT] == null) { $(this)[0].SetValue(scolnV, false); } else { $(this).val(jsrow[scolnT]); $(this)[0].SetValue(scolnV, true); }
        }
    });
    ptem123321.find(" input[type='text'][id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            var $inputctem1 = $(this);
            $inputctem1.val(jsrow[regetem[0]]);
            if ($inputctem1.attr("sTextField")) {
                var scolnT = $inputctem1.attr("R_F_T") ? $inputctem1.attr("R_F_T") : regetem[0].substr(0, regetem[0].length - 3) + "NME";
                var scolnV = $inputctem1.attr("R_F_V") ? $inputctem1.attr("R_F_V") : regetem[0].substr(0, regetem[0].length - 3) + "CDE";
                if ($inputctem1.attr('sShowField') == $inputctem1.attr('sValueField') && jsrow[scolnV] != null) {
                    $inputctem1.val(jsrow[scolnV]);
                }
                if ($inputctem1.attr('sShowField') == $inputctem1.attr('sTextField') && jsrow[scolnT] != null) {
                    $inputctem1.val(jsrow[scolnT]);
                } else {
                    $inputctem1.val(jsrow[regetem[0]]);
                }
                if (jsrow[scolnV] != null) { $inputctem1.attr('combValue', jsrow[scolnV]); } else { $inputctem1.attr('combValue', jsrow[regetem[0]]); }
                if (jsrow[scolnT] != null) { $inputctem1.attr('combText', jsrow[scolnT]); } else { $inputctem1.attr('combText', jsrow[regetem[0]]); }
            }
        }
    });
    ptem123321.find(" input[type='text'][id^='spn']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).val(jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" img[id^='img']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).attr("src", jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" input[type='hidden']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).val(jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" textarea[id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).val(jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" textarea[id^='spn']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).val(jsrow[regetem[0]]);
        }
    });
    ptem123321.find(" select[id^='dpl']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null && jsrow[regetem[0]] != null) {
            $(this).val(jsrow[regetem[0]]);
        }
    });
};
function BoundByJson(jrPanel, jrRet) {
    if (jrPanel == null || jrRet == null) return;
    $.each(jrPanel, function(idx, item) {
        BoundCotr(item, jrRet);
    });
};
function successajaxComm(data, successAjax) {
    //            try {
    if (data != '' && data != null) {
        var json = eval(data); //eval("(" + data + ")");
        $.each(json, function(idx, item) {
            //                        if (NotShowMask !== true) { ShowMask({ msg: '\u6B63\u5728\u7ED1\u5B9A\u6570\u636E\u5230\u5F53\u524D\u9875\u9762...' }); }
            BoundByJson(item.jpanel, item.jrow);
            //                        if (NotShowMask !== true) { ShowMask({ msg: '\u6B63\u5728\u6267\u884C\u524D\u53F0JS\u8BED\u53E5...' }); }
            if (!!(item.jscrip)) { eval(item.jscrip); }
            //                        if (NotShowMask !== true) { ShowMask({ msg: '\u6B63\u5728\u6267\u884C\u56DE\u8C03\u5B8C\u6210\u5904\u7406...' }); }
            if (successAjax != null) { successAjax(item.jcust, item.jrow); }
            if (item && item.jmsg != null && item.jmsg != "") { alert(item.jmsg); if (item.jmsg == "\u9519\u8BEF\uFF1A\u7528\u6237\u672A\u767B\u5F55\uFF01") { window.parent.parent.parent.location.href = shUrlBase + "wfThome.aspx"; } }
            if (item && item.jsclose != null && item.jsclose != "") { eval(item.jsclose); }
        });
    }
    ;
    //            } catch (e) {
//    HideMask();
    //                SA;
    //                alert('\u5BA2\u6237\u7AEFJS\u811A\u672C\u9519\u8BEF\uFF1A' + e.message);
    //            } HideMask(); //if (NotShowMask !== true) { if (cpid == null) $(document.body).unmask(); else $('#' + cpid).unmask(); }
};
function ajaxComm(jsParam, jsPost, successAjax, cpid, NotShowMask) {
    if (CurrActRadomstr == PageActRadomstr) {
        return;  // alert("系统后台正在处理，请不要重复提交！");
    }
    CurrActRadomstr = PageActRadomstr;
    if (jsPost == null) jsPost = new jsonRow();// 
    if (jsParam && pgtype) { jsParam.arrjson["PPAGE"] = pgtype; }
    if (jsParam && sCurrRadom) { jsParam.arrjson["sRadom"] = sCurrRadom; }
//    if (jsParam && jsParam.arrjson["PPAGE"] == null) { jsParam.arrjson["PPAGE"] = GetPageClass(); }
    if (cpid != null && (cpid == '' || $('#' + cpid).length <= 0)) cpid = null;
    $.ajax({
        type: "POST",
        mode: 'sync',
        url: shUrlBase + "pgcmd.axd", //shUrlBase + "UserControl/ajCommand.aspx",
        processData: true,
        data: { JSPARAM: jsParam.GetStr(), JSPOST: jsPost.GetStr() },
        beforeSend: function (XMLHttpRequest) {
                        if (NotShowMask !== true) { ShowMask({ msg: '\u6B63\u5728\u5904\u7406\u6570\u636E\uFF0C\u8BF7\u7B49\u5F85...' }); }
        },
                    success: function (data, textStatus) {
                        PageActRadomstr = GetRadom(16); //debugger;
            try {
                successajaxComm(data, successAjax);
            } catch (e) { } HideMask();
        },
        error: function () {
            PageActRadomstr = GetRadom(16); HideMask();
        }
    });
};
var PageActRadomstr = 'PageActRadomstr';
var CurrActRadomstr = '';
function doValidateData(caller) {
    if (!$.validationEngine.settings) {
        $.validationEngine.defaultSetting()
    }
    var rulesParsing = $(caller).attr('class');
    var rulesRegExp = /\[(.*)\]/;
    var getRules = rulesRegExp.exec(rulesParsing);
    if (getRules == null) { return ""; }
    var str = getRules[1];
    var pattern = /\W+/;
    var result = str.split(pattern);
    var validateCalll = $.validationEngine.validateCall(caller, result)
    return validateCalll;
};

//        complete: function(XMLHttpRequest, textStatus) { sa; if (cpid == null) $(document.body).parent().parent().unmask(); else $('#' + cpid).unmask(); },
function GetFormJson(pCid, jsPost) {
    if (jsPost == null) jsPost = new jsonRow();

    var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
    var ptem123321 = $("#" + pCid);
    if (ptem123321.size() <= 0) { return jsPost; }
    //    $("#" + pCid + " input[class*=validate]").each(function() {
    //        var regetem = this.id.match(regexp1);
    //        if (regetem != null) {
    //            var dddds = doValidateData(this); if (dddds) { alert("dddds"); }
    //        }
    //    });
    ptem123321.find(" input[type='checkbox'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            jsPost.AddCell(regetem[0], this.checked);
        }
    });
    ptem123321.find(" input[type='radio'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            jsPost.AddCell(regetem[0], this.checked);
        }
    });
    ptem123321.find(" input[type='text'][id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            jsPost.AddCell(regetem[0], $(this).val());
        }
    });
    ptem123321.find(" input[type='text'][id^='jlu']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            var $inputctem1 = $(this);
            var scolnT = $inputctem1.attr("R_F_T") ? $inputctem1.attr("R_F_T") : regetem[0].substr(0, regetem[0].length - 3) + "NME";
            var scolnV = $inputctem1.attr("R_F_V") ? $inputctem1.attr("R_F_V") : regetem[0].substr(0, regetem[0].length - 3) + "CDE";

            jsPost.AddCell(scolnV, $inputctem1.attr('combValue'));
            jsPost.AddCell(scolnT, $inputctem1.attr('combText'));

            if (!$inputctem1.attr('combValue') && !$inputctem1.attr('combText') && $inputctem1.val()) {
                jsPost.AddCell(regetem[0], $inputctem1.val());
            }
            //            var inputctem1 = $(this)[0];
            //            if (inputctem1.R_F_T) {
            //                jsPost.AddCell(inputctem1.R_F_T, $(this).val());
            //            }
            //            if (inputctem1.R_F_V) {
            //                jsPost.AddCell(inputctem1.R_F_V, inputctem1.EditValue);
            //            } else if (regetem[0].substr(regetem[0].length - 3, 3) == "NME") {
            //                jsPost.AddCell(regetem[0].substr(0, regetem[0].length - 3) + "CDE", $(this)[0].EditValue);
            //                jsPost.AddCell(regetem[0], $(this).val());
            //            }
            //            else if (regetem[0].substr(regetem[0].length - 3, 3) == "CDE") {
            //                jsPost.AddCell(regetem[0].substr(0, regetem[0].length - 3) + "NME", $(this).val());
            //                jsPost.AddCell(regetem[0], $(this)[0].EditValue);
            //            } else {
            //                if ($(this)[0].EditValue != "")
            //                    jsPost.AddCell(regetem[0], $(this)[0].EditValue);
            //                else
            //                    jsPost.AddCell(regetem[0], $(this).val());
            //            }
        }
    });
    ptem123321.find(" input[type='hidden']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            jsPost.AddCell(regetem[0], $(this).val());
        }
    });
    ptem123321.find(" img[id^='img']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            jsPost.AddCell(regetem[0], $(this).attr("src"));
        }
    });
    ptem123321.find(" textarea[id^='txt']").each(function () {
        var regetem = this.id.match(regexp1);
        if (regetem != null) { 
            jsPost.AddCell(regetem[0], replaceAll($(this).val(), "\n", "\r\n"));
        }
    });
    ptem123321.find(" select[id^='dpl']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            var vtem111 = $(this).val() ? $(this).val() : "";
            if (regetem[0].substr(regetem[0].length - 3, 3) == "CDE" || regetem[0].substr(regetem[0].length - 3, 3) == "NME") {
                var scolnT = regetem[0].substr(0, regetem[0].length - 3) + "NME";
                var scolnV = regetem[0].substr(0, regetem[0].length - 3) + "CDE";
                jsPost.AddCell(scolnV, vtem111);
                jsPost.AddCell(scolnT, $(this).find(" option[value='" + encodeURIComponent(vtem111) + "']").text());
            }
            jsPost.AddCell(regetem[0], vtem111);
        }
    });
    ptem123321.find(" select[id^='lsb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            var vtem111 = GetLsbValue(this.id);
            vtem111 = vtem111 ? vtem111 : "";
            jsPost.AddCell(regetem[0], vtem111);
        }
    }); return jsPost;
};
var sPageEditMode = 'VIEW';
function SetEditMode(pCid, sMode) {
    var blDisab = sMode == "VIEW";
    var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
    var ptem123321 = $("#" + pCid);
    if (ptem123321.size() <= 0) { return; }
    ptem123321.find(" input[type='checkbox'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("disabled", blDisab);
        }
    });
    ptem123321.find(" input[type='radio'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("disabled", blDisab);
        }
    });
    ptem123321.find(" input[type='text'][id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("readOnly", blDisab);
            //            if (blDisab) { $(this).addClass('InputDisable'); } else { $(this).removeClass('InputDisable'); }
        }
    });
    ptem123321.find(" input[type='text'][id^='jlu']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            //            $(this).autocomplete({
            //                readonly: blDisab
            //            });
            $(this).attr("readOnly", blDisab);
        }
    });
    ptem123321.find(" textarea[id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("readOnly", blDisab);
            if ($(this)[0].editor != null) $(this)[0].editor.toggleReadonly(blDisab);
        }
    });
    ptem123321.find(" select[id^='dpl']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("disabled", blDisab);
        }
    });
    ptem123321.find(" select[id^='lsb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("disabled", blDisab);
        }
    });// sPageEditMode = sMode;
};
function SetCEmpty(pCid) {
    var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
    var ptem123321 = $("#" + pCid);
    if (ptem123321.size() <= 0) { return; }
    ptem123321.find(" input[type='checkbox'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("checked", false);
        }
    });
    ptem123321.find(" input[type='radio'][id^='ckb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr("checked", false);
        }
    });
    ptem123321.find(" input[type='text'][id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).val("");
        }
    });
    ptem123321.find(" input[type='text'][id^='jlu']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).attr('combValue', '').attr('combText', '').val('');
        }
    });
    ptem123321.find(" textarea[id^='txt']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).val("");
        }
    });
    ptem123321.find(" select[id^='dpl']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).val("");
        }
    });
    ptem123321.find(" select[id^='lsb']").each(function() {
        var regetem = this.id.match(regexp1);
        if (regetem != null) {
            $(this).val("");
        }
    });
};
function GetLsbValue(sId, Lsbslect) {
    var Lsbslect = Lsbslect || $("#" + sId + " option");
    var sSelected = "";
    if (Lsbslect && Lsbslect.size() > 0) {
        $.each(Lsbslect, function(id, own) {
            sSelected += sSelected == "" ? this.value : "," + this.value;
        });
    }
    return sSelected;
};
function SetBtnEnable(tCids, fCids) {
    var arrtem1 = tCids.split(',');
    for (var i = 0; i < arrtem1.length; i++) {
        if (arrtem1[i]) { var $_tem1232 = $("#" + arrtem1[i]); if ($_tem1232.length <= 0) { continue; } if ($_tem1232[0].tagName == "TEXTAREA" || $_tem1232[0].tagName == "INPUT" && $_tem1232[0].type == "text") { $_tem1232.attr("readOnly", false); } else { $_tem1232.attr("disabled", false); } }
    }
    if (fCids == null) return;
    var arrtem2 = fCids.split(',');
    for (var i = 0; i < arrtem2.length; i++) {
        if (arrtem2[i]) { var $_tem1232 = $("#" + arrtem2[i]); if ($_tem1232.length <= 0) { continue; } if ($_tem1232[0].tagName == "TEXTAREA" || $_tem1232[0].tagName == "INPUT" && $_tem1232[0].type == "text") { $_tem1232.attr("readOnly", true); } else { $_tem1232.attr("disabled", true); } }
    }
};
function cSetCtrlV(sCid, sValue, sVNme) {
//    if (sCid == "txtNOTIFY1") {asdfasdfasdf;  alert(sValue); }
    var cTems = $('#' + sCid);
    var regexp1 = new RegExp("[A-Z|0-9|_]{3,}");
    if (cTems != null && cTems.length > 0) {
        if (cTems[0].tagName == "SPAN" || cTems[0].tagName == "DIV" || cTems[0].tagName == "A") {
            cTems.html(sValue);
        } else if (cTems[0].tagName == "INPUT" && cTems[0].type == "checkbox") {
            cTems.attr("checked", (sValue == "true" || sValue == "True"));
        } else if (cTems[0].tagName == "INPUT" && cTems[0].type == "radio") {
            if (sValue == "true" || sValue == "True") { cTems.attr("checked", "checked"); } //else { cTems.removeAttr("checked"); }
        } else if (cTems[0].tagName == "IMG") {
            cTems.attr("src", sValue);
        } else if (cTems[0].tagName == "INPUT" && cTems[0].id.substr(0, 3) == "jlu") {
            var regetem = sCid.match(regexp1);
            if (regetem != null && sVNme != null) {
                var $inputctem1 = cTems;
                var scolnT = $inputctem1.attr("R_F_T") ? $inputctem1.attr("R_F_T") : regetem[0].substr(0, regetem[0].length - 3) + "NME";
                var scolnV = $inputctem1.attr("R_F_V") ? $inputctem1.attr("R_F_V") : regetem[0].substr(0, regetem[0].length - 3) + "CDE";
                if ($inputctem1.attr('sShowField') == $inputctem1.attr('sValueField') && sValue != null) {
                    $inputctem1.val(sValue);
                }
                else if ($inputctem1.attr('sShowField') == $inputctem1.attr('sTextField') && sVNme != null) {
                    $inputctem1.val(sVNme);
                } else {
                    $inputctem1.val(sValue);
                }
                cTems.attr('combValue', sValue).attr('combText', sVNme);
            } else {
                cTems.attr('combValue', sValue).val(sValue).search();
            }
        } else if (cTems[0].tagName == "SELECT") {
            if ($.browser.msie && $.browser.version == "6.0") {

                setTimeout(function() {

                    cTems.each(function() {
                        for (var i = 0; i < this.options.length; i++) {

                            if (this.options[i].value == sValue) {

                                this.options[i].selected = "selected";

                                break;

                            }

                        }

                    });

                }, 1000);
                //            
                //                cTems.find('option').attr('selected', false);
                //                setTimeout(function() { var temdskf1 = cTems.find('option[value="' + sValue + '"]')[0];if(temdskf1!=null) temdskf1.selected = true; }, 10);
            } else {
                cTems.val(sValue);
            }
        } else {
            cTems.val(sValue);
        }
    }
//    if (sCid == "txtNOTIFY1") { alert($("#txtNOTIFY1").val()); }
};
//function InitSys(sSys) {
//    if (typeof (Sys.WebForms) != "undefined") {
//        var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_initializeRequest(ajaxinitializeRequest); prm.add_pageLoaded(ajaxpageLoaded); prm.add_endRequest(ajaxEndRequest);
//    }
//}
//function ajaxinitializeRequest(sender, args) {
//    $(document.body).mask("Waiting...");
//}
//function ajaxpageLoaded(sender, args) {
//    $(document.body).unmask();
//}
//function ajaxEndRequest(sender, args) {
//    $(document.body).unmask();
//    if (args.get_error() != undefined) {
//        args.set_errorHandled(true);
//        var LastError = args._response._xmlHttpRequest.responseText; alertLastErr(LastError);
//    }
//}
//function alertLastErr(LastError) {
//    if (LastError.indexOf("title") < LastError.indexOf("/title")) {
//        LastError = LastError.substring(LastError.indexOf("title") + 6, LastError.indexOf("/title", LastError.indexOf("title")) - 1);
//    } args = null;
//    window.alert(LastError);
//};
function OpenHelp() {
    OpenBox(null, null, null, null, { href: shUrlBase + "Bse/wfHelpShow.aspx?NO=" + GetPageClass(), title: document.title + '--help', iframe: true, overlayClose: false, width: "92%", height: "92%" });
};
function scrcFloatDivByDivId(sId, itoptm, irighttm) {
    var $_tem1 = $('#' + sId);
    if ($_tem1.length > 0) {
        $_tem1.css("position", "absolute");
        var wimHeight = parseInt($_tem1.height());
        var wimWidth = parseInt($_tem1.width()); if (itoptm == null) itoptm = 1; if (irighttm == null) irighttm = 0;
        var newTop = $(document).scrollTop() + itoptm;
        var newLeft = $(document).scrollLeft() + $(window).width() - wimWidth - irighttm;
        if (!$_tem1.is(":hidden")) {
            if ($_tem1.offset().top != newTop || $_tem1.offset().left != newLeft) {
                $_tem1.animate({ "top": newTop, "left": newLeft }, 200);
            }
        } else {
            $_tem1.css({ "top": newTop, "left": newLeft });
        }
    }
};
function cFloatDivByDivId(sId, itoptm, irighttm) {
    var $_tem1 = $('#' + sId);
    if ($_tem1.length > 0) {
        $_tem1.everyTime(300, "scrcFloatDiv", function() { scrcFloatDivByDivId(sId, itoptm, irighttm); });
    }
};
function ShowToolBarRT() {
    if ($("#btnToolBarRTDiv1").length <= 0) {
        var $rettem1 = CreateBtnDiv('btnToolBarRTDiv1', "\u70B9\u51FB\u5C55\u5F00\u5DE5\u5177\u6761", "", "images/desktop/S_Suppliers-24.gif");
        $rettem1.css('width', '24px').css('height', '24px').fadeTo(100, 0.2).css("z-index", parseInt(new Date().getTime() / 1000) - 4);
        cFloatDivByDivId('btnToolBarRTDiv1');
        AddShowToolBarRT(null, '', '\u663E\u793A\u5E2E\u52A9\u4FE1\u606F', "OpenHelp();", 'images/desktop/Gif16/help.gif');
        //        AddShowToolBarRT(null, 'btnToolBarRTbtnDiv11', '', "window.location.reload(true);", '', "<img src=\"" + shUrlBase + "images/desktop/Png16/16-em-check.png\" height=\"14px\" align=\"absmiddle\" /> ");
        AddShowToolBarRT(null, 'btnToolBarRTbtnDiv0', "\u5237\u65B0\u9875\u9762", "window.location.reload(true);", "images/desktop/Gif16/Refresh.gif");
        AddShowToolBarRT(null, 'btnToolBarRTbtnDiv1', "\u5728\u65B0\u7684\u9875\u9762\u4E2D\u6253\u5F00\u5F53\u524D\u9875", "ShowChildForm(window.name, window.location.href);", "images/desktop/Png16/page.png");
        var $rettem2 = $("#btnToolBarRTCtDiv1").hide();
        var _timeout;
        $rettem1.hover(function() {
            clearTimeout(_timeout); $rettem2.fadeIn("slow").show("slow");
        },
        function() {
            clearTimeout(_timeout); _timeout = setTimeout(' $("#btnToolBarRTCtDiv1").fadeOut("slow").hide("slow")', 1000);
        });
        $rettem2.hover(function() {
            clearTimeout(_timeout); $rettem2.fadeIn("slow").show("slow");
        },
        function() {
            clearTimeout(_timeout); _timeout = setTimeout(' $("#btnToolBarRTCtDiv1").fadeOut("slow").hide("slow")', 1000);
        });
        //        $rettem1.poshytip({
        //            content: function() { return $("#btnToolBarRTCtDiv1"); },
        //            className: 'tip-yellowsimple',
        //            alignTo: 'target',
        //            alignX: 'left',
        //            alignY: 'center',
        //            offsetX: 5
        //        });
    }
};
function AddShowToolBarRT(_jqoBtn, sId, sTit, sJstm, sBgImgUrl, sAtxt) {
    var $rettem2 = $('#btnToolBarRTCtDiv1');
    if ($("#btnToolBarRTCtDiv1").length <= 0) {
        var dscript = document.createElement("div"); dscript.id = "btnToolBarRTCtDiv1";
        $("body").append(dscript); $rettem2 = $("#btnToolBarRTCtDiv1"); //.css("filter", "alpha(opacity=30)").css("-moz-opacity", "0.6").css("opacity", "0.6");
        $rettem2.css({ width: '90%', height: '18px', overflow: 'hidden', cursor: "", opacity: 0 }).fadeTo(100, 1);
        cFloatDivByDivId('btnToolBarRTCtDiv1', 2, 30);
    }
    if (_jqoBtn == null || !_jqoBtn) {
        if (sAtxt != null && sAtxt) {
            _jqoBtn = $(GetALink(sAtxt, null, null, sJstm)).css("float", "right");
        } else {
            if (!sId || sId == null) { sId = GetRadom(10); }
            _jqoBtn = CreateBtnDiv(sId, sTit, sJstm, sBgImgUrl).css("float", "right");
        }
    }
    $rettem2.append(_jqoBtn).append($("<div>&nbsp;</div>").css('width', '5px').css('height', '16px').css("float", "right"));
    return _jqoBtn;
};
function CreateBtnDiv(sId, sTit, sJstm, sBgImgUrl) {
    var $rettem1 = $("#" + sId);
    if ($rettem1.length <= 0) {
        var dscript = document.createElement("div"); dscript.id = sId; dscript.title = sTit;
        $("body").append(dscript); $rettem1 = $("#" + sId);
        $rettem1.hover(function() { $(this).fadeTo(300, 1.0); },
            function() {
                $(this).fadeTo(300, 0.6);
            }).click(function() {
                eval(sJstm);
            }).css("cursor", "hand").css('background-image', "url(" + shUrlBase + sBgImgUrl + ")").css('width', '16px').css('height', '16px').fadeTo(300, 0.4);
    }
    return $rettem1;
};
function getImgByStatus(sStatus) {
    if (sStatus && sStatus.toLowerCase() == "true") { sStatus = "1"; } else if (sStatus == null || !sStatus || isNaN(sStatus)) { sStatus = "0"; } else if (sStatus) { sStatus = parseInt(sStatus); } else { return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; }
    return '<img src="' + shUrlBase + 'images/Gif16/Label' + sStatus + '.gif" height="14px" align="absmiddle" />';
};
$(window).load(function() {
    var pclasstem1 = GetPageClass().toLowerCase(); // if (pclasstem1 != "" && pclasstem1 != "wfthome" && pclasstem1 != "wfconditionsetlistselect") ShowToolBarRT();
    //    if (typeof (Sys) != "undefined") InitSys(Sys); 
    //    //you jian jing yong
    //    $(document).bind("contextmenu", function(e) {
    //        return false;
    //        });
    SettextareaCss();
});
function SettextareaCss() {
    //    $("input[type='text']").each(function() {
    //    var iwidthtem =$(this).width()- 4;
    //        $(this).width(iwidthtem);
    //    });
    //    $("textarea").each(function() {
    //    var iwidthtem =$(this).width()- 4;
    //        $(this).width(iwidthtem);
    //    });
    $(" input[type='text']").addClass('win7input');
    $(" input[type='password']").addClass('win7input');
    $("textarea").addClass('win7input');
};


function initShowDocSecl() {
    return;
    var sHtmltem1 = '';
    sHtmltem1 += '<div id="dvDocSeclTemList1" style="width: 18px;">';
    sHtmltem1 += '   <div style="width: 120px; float: left; height: 260px; display: none; border: #cc0000 1px solid;';
    sHtmltem1 += '        background-color: #eee; padding: 3px;" class="dleft">';
    sHtmltem1 += '        <div style="width: 112px;">';
    sHtmltem1 += '            <span style="color: #3F0101; float: left;">已选货票列表 </span><span style="float: right;">';
    sHtmltem1 += '                X</span></div>';
    sHtmltem1 += '        <div>';
    sHtmltem1 += '            <select size="4" name="lstDocSeclTemList1" id="lstDocSeclTemList1" multiple="multiple" style="height: 220px; width: 110px;"> ';
    sHtmltem1 += '            </select>';
    sHtmltem1 += '        </div>';
    sHtmltem1 += '        <div>';
    sHtmltem1 += '            <center>';
    sHtmltem1 += '                <input type="button" onclick="GetDocSeclList(\'2\');" value="清空" id="Button2" />';
    sHtmltem1 += '                <input type="button" onclick="delDocSeclListItem();" value="删除" id="Button3" /></center>';
    sHtmltem1 += '        </div>';
    sHtmltem1 += '    </div>';
    sHtmltem1 += '    <div style="width: 16px; float: right;  display: none; border: gray 1px solid;';
    sHtmltem1 += '        background-color: Aqua; padding: 3px; height: 43px;" class="dright">';
    sHtmltem1 += '        公文包</div>';
    sHtmltem1 += '</div>';
    $("body").append($(sHtmltem1));
    SetDocSeclPosition();
    $("#dvDocSeclTemList1").bgIframe({ opacity: false }).css({ opacity: 0.8, "position": "absolute", "display": "block", "z-index": parseInt(new Date().getTime() / 100) + 210 });
    setInterval(function() { SetDocSeclPosition(); }, 200);
    GetDocSeclList("1");
    $("#dvDocSeclTemList1").hover(function() {
        if ($(this).find(".dleft").is(":hidden")) {
            $(this).width($(this).find(".dleft").eq(0).width());
            $(this).find(".dleft").show();
            $(this).find(".dright").hide();

            GetDocSeclList("1");
        }
    },
    function() {
        if (!$(this).find(".dleft").is(":hidden")) {
            $(this).find(".dleft").hide(50);
            $(this).find(".dright").show();
            $(this).width($(this).find(".dright").eq(0).width());
        }
    }).find(".dright").show();
};
function AddDocSeclListItem(sValuetem1, sTexttem1) {
    var $_nodetem1 = $("<span style=\"float:left;word-break: keep-all;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;border-style: solid;border-width: 1px;background-color: #F3F6F9;border-color: #E2E7EE;margin: 2px;padding:3px;\" scode=\"" + sValuetem1 + "\" title=\"" + sTexttem1 + "\">&nbsp;" + sTexttem1 + "</span>")
            .css({ "cursor": "default", "z-index": parseInt(new Date().getTime() / 1000) - 4 });
    $("body").append($_nodetem1);
    var mousePos = mouseCoords();
    var $ctem1 = $("#dvDocSeclTemList1");
    var inewtop1 = $ctem1.offset().top + 50;
    var inewleft1 = $ctem1.offset().left;
    $_nodetem1.css({ top: mousePos.y, left: mousePos.x, position: "absolute", opacity: 0.6 });
    $_nodetem1.animate({ top: inewtop1, left: inewleft1, opacity: 1 }, 350, function() { $(this).css({ position: "" }); $(this).remove(); });
    GetDocSeclList("1", sValuetem1, sTexttem1);
};
function delDocSeclListItem() {
    var vSelect = $("#lstDocSeclTemList1 option:selected");
    var sValuetem2 = GetLsbValue(null, vSelect);
    GetDocSeclList("3", sValuetem2);
};
function GetDocSeclListValue() {
    return GetLsbValue('lstDocSeclTemList1');
};
function GetDocSeclList(sLable, sNewValue, sNewTxt) {
    $.ajax({
        // try to leverage ajaxQueue plugin to abort previous requests
        mode: "sync",
        // limit abortion to this input abort
        port: "dvDocSeclTemList1",
        url: shUrlBase + "pgajax.axd?GETDOCSELLIST=" + sLable, //shUrlBase + "UserControl/SetClientInfo.aspx?GETDOCSELLIST=" + sLable,
        data: {
            sValue: sNewValue || '',
            sTxt: sNewTxt || ''
        },
        success: function(data) {
            $("#lstDocSeclTemList1").empty().append($(data));
        }
    });
};
function SetDocSeclPosition() {
    var $ctem1 = $("#dvDocSeclTemList1");
    var iLefttem1 = $(window).width() - $ctem1.outerWidth() + $(document).scrollLeft();
    var iToptem1 = $(document).scrollTop() + 30;  //Math.floor($(window).height() / 3);
    if ($ctem1.offset().top != iToptem1 || $ctem1.offset().left != iLefttem1) {
        $ctem1.animate({ "left": iLefttem1, "top": iToptem1 }, 150);
    }
};

function SetStatusShowA(sDivId) {
    var $divssSShow = $("#" + sDivId);
    $divssSShow.find("span").each(function() {
        var $temdom1 = $(this);
        var htmltem1 = $temdom1.html();
        if ($temdom1.attr("stv")) {
            $temdom1.click(function () {
                if ($("#btnSave") && $("#btnSave").attr("disabled") != "disabled") {
                    alert("请先保存！"); return;
                }
                btnDo("setStatus_" + $temdom1.attr("stv"));
            })
                    .hover(function() {
                        $temdom1.addClass("ExecHover");
                    },
                    function() {
                        if ($temdom1.hasClass("ExecHover")) { $temdom1.removeClass("ExecHover"); }
                    })
                    .attr("title", "点击改变执行状态为【" + htmltem1 + "】！");
        }
    });
};

var GtGrid1Action = "START";
function ShowUserJobList() {
    GtGrid1Action = "doShowUserJobList";
    var opart = GetGtParam();
    ajaxComm(opart, null, null, null, true);
    GtGrid1Action = "";
};

function getProcessHtml(iCount, value, stitle) {
    var shtmlt1 = "";
    for (var i = 0; i < iCount; i++) {
        if (value && value >= i) {
            shtmlt1 += "<span class='sLight1' >&nbsp;</span>";
        } else {
            shtmlt1 += "<span class='sLight0' >&nbsp;</span>";
        }
    }
    return "<span title='" + (stitle || "") + "'>" + shtmlt1 + "</span>";
};

/*屏蔽Backspace，输入内容不屏蔽*/
$(document) && $(document).bind("keydown",
function () {
    if (document.activeElement && (document.activeElement.type == "text" || document.activeElement.type == "password" || document.activeElement.type == "textarea" || document.activeElement.tagName == "TEXTAREA")) {
        if ((event.keyCode == 116) ||            //屏蔽 F5 刷新键 
           (event.ctrlKey && event.keyCode == 82))//Ctrl + R 
        {
            event.keyCode = 0;
            event.returnValue = false;
        }
        if (document.activeElement.readOnly == true) {
            if ((event.keyCode == 8) ||             //屏蔽退格删除键 
           (event.keyCode == 116) ||                  //屏蔽 F5 刷新键 
           (event.ctrlKey && event.keyCode == 82)) { //Ctrl + R 
                event.keyCode = 0;
                event.returnValue = false;
            }
        }
    }
    else {
        if ((event.keyCode == 8) ||             //屏蔽退格删除键 
           (event.keyCode == 116) ||                  //屏蔽 F5 刷新键 
           (event.ctrlKey && event.keyCode == 82)) { //Ctrl + R 
            event.keyCode = 0;
            event.returnValue = false;
        }
    }
});



/*  Copyright Mihai Bazon, 2002-2005  |  www.bazon.net/mishoo
* -----------------------------------------------------------
*
* The DHTML Calendar, version 1.0 "It is happening again"
*
* Details and latest version at:
* www.dynarch.com/projects/calendar
*
* This script is developed by Dynarch.com.  Visit us at www.dynarch.com.
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*/

// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $

/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
    // member variables
    this.activeDiv = null;
    this.currentDateEl = null;
    this.getDateStatus = null;
    this.getDateToolTip = null;
    this.getDateText = null;
    this.timeout = null;
    this.onSelected = onSelected || null;
    this.onClose = onClose || null;
    this.dragging = false;
    this.hidden = false;
    this.minYear = 1970;
    this.maxYear = 2050;
    this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
    this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
    this.isPopup = true;
    this.weekNumbers = true;
    this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
    this.showsOtherMonths = false;
    this.dateStr = dateStr;
    this.ar_days = null;
    this.showsTime = true;
    this.time24 = true;
    this.yearStep = 2;
    this.hiliteToday = true;
    this.multiple = null;
    // HTML elements
    this.table = null;
    this.element = null;
    this.tbody = null;
    this.firstdayname = null;
    // Combo boxes
    this.monthsCombo = null;
    this.yearsCombo = null;
    this.hilitedMonth = null;
    this.activeMonth = null;
    this.hilitedYear = null;
    this.activeYear = null;
    // Information
    this.dateClicked = false;

    // one-time initializations
    if (typeof Calendar._SDN == "undefined") {
        // table of short day names
        if (typeof Calendar._SDN_len == "undefined")
            Calendar._SDN_len = 3;
        var ar = new Array();
        for (var i = 8; i > 0; ) {
            ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
        }
        Calendar._SDN = ar;
        // table of short month names
        if (typeof Calendar._SMN_len == "undefined")
            Calendar._SMN_len = 3;
        ar = new Array();
        for (var i = 12; i > 0; ) {
            ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
        }
        Calendar._SMN = ar;
    }
};

// ** constants

/// "static", needed for event handlers.
Calendar._C = null;

/// detect a special case of "web browser"
Calendar.is_ie = (/msie/i.test(navigator.userAgent) &&
		   !/opera/i.test(navigator.userAgent));

Calendar.is_ie5 = (Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent));

/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);

/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
//        library, at some point.

Calendar.getAbsolutePos = function (el) {
    var SL = 0, ST = 0;
    var is_div = /^div$/i.test(el.tagName);
    if (is_div && el.scrollLeft)
        SL = el.scrollLeft;
    if (is_div && $(el).scrollTop())
        ST = $(el).scrollTop;
    var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
    if (el.offsetParent) {
        var tmp = this.getAbsolutePos(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;
    }
    return r;
};

Calendar.isRelated = function (el, evt) {
    var related = evt.relatedTarget;
    if (!related) {
        var type = evt.type;
        if (type == "mouseover") {
            related = evt.fromElement;
        } else if (type == "mouseout") {
            related = evt.toElement;
        }
    }
    while (related) {
        if (related == el) {
            return true;
        }
        related = related.parentNode;
    }
    return false;
};

Calendar.removeClass = function (el, className) {
    if (!(el && el.className)) {
        return;
    }
    var cls = el.className.split(" ");
    var ar = new Array();
    for (var i = cls.length; i > 0; ) {
        if (cls[--i] != className) {
            ar[ar.length] = cls[i];
        }
    }
    el.className = ar.join(" ");
};

Calendar.addClass = function (el, className) {
    Calendar.removeClass(el, className);
    el.className += " " + className;
};

// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function (ev) {
    var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
    while (f.nodeType != 1 || /^div$/i.test(f.tagName))
        f = f.parentNode;
    return f;
};

Calendar.getTargetElement = function (ev) {
    var f = Calendar.is_ie ? window.event.srcElement : ev.target;
    while (f.nodeType != 1)
        f = f.parentNode;
    return f;
};

Calendar.stopEvent = function (ev) {
    ev || (ev = window.event);
    if (Calendar.is_ie) {
        ev.cancelBubble = true;
        ev.returnValue = false;
    } else {
        ev.preventDefault();
        ev.stopPropagation();
    }
    return false;
};

Calendar.addEvent = function (el, evname, func) {
    if (el.attachEvent) { // IE
        el.attachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
        el.addEventListener(evname, func, true);
    } else {
        el["on" + evname] = func;
    }
};

Calendar.removeEvent = function (el, evname, func) {
    if (el.detachEvent) { // IE
        el.detachEvent("on" + evname, func);
    } else if (el.removeEventListener) { // Gecko / W3C
        el.removeEventListener(evname, func, true);
    } else {
        el["on" + evname] = null;
    }
};

Calendar.createElement = function (type, parent) {
    var el = null;
    if (document.createElementNS) {
        // use the XHTML namespace; IE won't normally get here unless
        // _they_ "fix" the DOM2 implementation.
        el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
    } else {
        el = document.createElement(type);
    }
    if (typeof parent != "undefined") {
        parent.appendChild(el);
    }
    return el;
};

// END: UTILITY FUNCTIONS

// BEGIN: CALENDAR STATIC FUNCTIONS

/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function (el) {
    with (Calendar) {
        addEvent(el, "mouseover", dayMouseOver);
        addEvent(el, "mousedown", dayMouseDown);
        addEvent(el, "mouseout", dayMouseOut);
        addEvent(el, "click", function (event) {
            event = event || window.event;
            Calendar.stopEvent(event);
        });
        if (is_ie) {
            addEvent(el, "dblclick", dayMouseDblClick);
            el.setAttribute("unselectable", true);
        }
    }
};

Calendar.findMonth = function (el) {
    if (typeof el.month != "undefined") {
        return el;
    } else if (typeof el.parentNode.month != "undefined") {
        return el.parentNode;
    }
    return null;
};

Calendar.findYear = function (el) {
    if (typeof el.year != "undefined") {
        return el;
    } else if (typeof el.parentNode.year != "undefined") {
        return el.parentNode;
    }
    return null;
};

Calendar.showMonthsCombo = function () {
    var cal = Calendar._C;
    if (!cal) {
        return false;
    }
    var cal = cal;
    var cd = cal.activeDiv;
    var mc = cal.monthsCombo;
    if (cal.hilitedMonth) {
        Calendar.removeClass(cal.hilitedMonth, "hilite");
    }
    if (cal.activeMonth) {
        Calendar.removeClass(cal.activeMonth, "active");
    }
    var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
    Calendar.addClass(mon, "active");
    cal.activeMonth = mon;
    var s = mc.style;
    s.display = "block";
    if (cd.navtype < 0)
        s.left = cd.offsetLeft + "px";
    else {
        var mcw = mc.offsetWidth;
        if (typeof mcw == "undefined")
        // Konqueror brain-dead techniques
            mcw = 50;
        s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
    }
    s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};

Calendar.showYearsCombo = function (fwd) {
    var cal = Calendar._C;
    if (!cal) {
        return false;
    }
    var cal = cal;
    var cd = cal.activeDiv;
    var yc = cal.yearsCombo;
    if (cal.hilitedYear) {
        Calendar.removeClass(cal.hilitedYear, "hilite");
    }
    if (cal.activeYear) {
        Calendar.removeClass(cal.activeYear, "active");
    }
    cal.activeYear = null;
    var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
    var yr = yc.firstChild;
    var show = false;
    for (var i = 12; i > 0; --i) {
        if (Y >= cal.minYear && Y <= cal.maxYear) {
            yr.innerHTML = Y;
            yr.year = Y;
            yr.style.display = "block";
            show = true;
        } else {
            yr.style.display = "none";
        }
        yr = yr.nextSibling;
        Y += fwd ? cal.yearStep : -cal.yearStep;
    }
    if (show) {
        var s = yc.style;
        s.display = "block";
        if (cd.navtype < 0)
            s.left = cd.offsetLeft + "px";
        else {
            var ycw = yc.offsetWidth;
            if (typeof ycw == "undefined")
            // Konqueror brain-dead techniques
                ycw = 50;
            s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
        }
        s.top = (cd.offsetTop + cd.offsetHeight) + "px";
    }
};

// event handlers

Calendar.tableMouseUp = function (ev) {
    var cal = Calendar._C;
    if (!cal) {
        return false;
    }
    if (cal.timeout) {
        clearTimeout(cal.timeout);
    }
    var el = cal.activeDiv;
    if (!el) {
        return false;
    }
    var target = Calendar.getTargetElement(ev);
    ev || (ev = window.event);
    Calendar.removeClass(el, "active");
    if (target == el || target.parentNode == el) {
        Calendar.cellClick(el, ev);
    }
    var mon = Calendar.findMonth(target);
    var date = null;
    if (mon) {
        date = new Date(cal.date);
        if (mon.month != date.getMonth()) {
            date.setMonth(mon.month);
            cal.setDate(date);
            cal.dateClicked = false;
            cal.callHandler();
        }
    } else {
        var year = Calendar.findYear(target);
        if (year) {
            date = new Date(cal.date);
            if (year.year != date.getFullYear()) {
                date.setFullYear(year.year);
                cal.setDate(date);
                cal.dateClicked = false;
                cal.callHandler();
            }
        }
    }
    with (Calendar) {
        removeEvent(document, "mouseup", tableMouseUp);
        removeEvent(document, "mouseover", tableMouseOver);
        removeEvent(document, "mousemove", tableMouseOver);
        cal._hideCombos();
        _C = null;
        return stopEvent(ev);
    }
};

Calendar.tableMouseOver = function (ev) {
    var cal = Calendar._C;
    if (!cal) {
        return;
    }
    var el = cal.activeDiv;
    var target = Calendar.getTargetElement(ev);
    if (target == el || target.parentNode == el) {
        Calendar.addClass(el, "hilite active");
        Calendar.addClass(el.parentNode, "rowhilite");
    } else {
        if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
            Calendar.removeClass(el, "active");
        Calendar.removeClass(el, "hilite");
        Calendar.removeClass(el.parentNode, "rowhilite");
    }
    ev || (ev = window.event);
    if (el.navtype == 50 && target != el) {
        var pos = Calendar.getAbsolutePos(el);
        var w = el.offsetWidth;
        var x = ev.clientX;
        var dx;
        var decrease = true;
        if (x > pos.x + w) {
            dx = x - pos.x - w;
            decrease = false;
        } else
            dx = pos.x - x;

        if (dx < 0) dx = 0;
        var range = el._range;
        var current = el._current;
        var count = Math.floor(dx / 10) % range.length;
        for (var i = range.length; --i >= 0; )
            if (range[i] == current)
                break;
        while (count-- > 0)
            if (decrease) {
                if (--i < 0)
                    i = range.length - 1;
            } else if (++i >= range.length)
                i = 0;
        var newval = range[i];
        el.innerHTML = newval;

        cal.onUpdateTime();
    }
    var mon = Calendar.findMonth(target);
    if (mon) {
        if (mon.month != cal.date.getMonth()) {
            if (cal.hilitedMonth) {
                Calendar.removeClass(cal.hilitedMonth, "hilite");
            }
            Calendar.addClass(mon, "hilite");
            cal.hilitedMonth = mon;
        } else if (cal.hilitedMonth) {
            Calendar.removeClass(cal.hilitedMonth, "hilite");
        }
    } else {
        if (cal.hilitedMonth) {
            Calendar.removeClass(cal.hilitedMonth, "hilite");
        }
        var year = Calendar.findYear(target);
        if (year) {
            if (year.year != cal.date.getFullYear()) {
                if (cal.hilitedYear) {
                    Calendar.removeClass(cal.hilitedYear, "hilite");
                }
                Calendar.addClass(year, "hilite");
                cal.hilitedYear = year;
            } else if (cal.hilitedYear) {
                Calendar.removeClass(cal.hilitedYear, "hilite");
            }
        } else if (cal.hilitedYear) {
            Calendar.removeClass(cal.hilitedYear, "hilite");
        }
    }
    return Calendar.stopEvent(ev);
};

Calendar.tableMouseDown = function (ev) {
    if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
        return Calendar.stopEvent(ev);
    }
};

Calendar.calDragIt = function (ev) {
    var cal = Calendar._C;
    if (!(cal && cal.dragging)) {
        return false;
    }
    var posX;
    var posY;
    if (Calendar.is_ie) {
        posY = window.event.clientY + $(document).scrollTop();
        posX = window.event.clientX + $(document).scrollLeft();
    } else {
        posX = ev.pageX;
        posY = ev.pageY;
    }
    cal.hideShowCovered();
    var st = cal.element.style;
    st.left = (posX - cal.xOffs) + "px";
    st.top = (posY - cal.yOffs) + "px";
    return Calendar.stopEvent(ev);
};

Calendar.calDragEnd = function (ev) {
    var cal = Calendar._C;
    if (!cal) {
        return false;
    }
    cal.dragging = false;
    with (Calendar) {
        removeEvent(document, "mousemove", calDragIt);
        removeEvent(document, "mouseup", calDragEnd);
        tableMouseUp(ev);
    }
    cal.hideShowCovered();
};

Calendar.dayMouseDown = function (ev) {
    var el = Calendar.getElement(ev);
    if (el.disabled) {
        return false;
    }
    var cal = el.calendar;
    cal.activeDiv = el;
    Calendar._C = cal;
    if (el.navtype != 300) with (Calendar) {
        if (el.navtype == 50) {
            el._current = el.innerHTML;
            addEvent(document, "mousemove", tableMouseOver);
        } else
            addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
        addClass(el, "hilite active");
        addEvent(document, "mouseup", tableMouseUp);
    } else if (cal.isPopup) {
        cal._dragStart(ev);
    }
    if (el.navtype == -1 || el.navtype == 1) {
        if (cal.timeout) clearTimeout(cal.timeout);
        cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
    } else if (el.navtype == -2 || el.navtype == 2) {
        if (cal.timeout) clearTimeout(cal.timeout);
        cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
    } else {
        cal.timeout = null;
    }
    return Calendar.stopEvent(ev);
};

Calendar.dayMouseDblClick = function (ev) {
    Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
    if (Calendar.is_ie) {
        document.selection.empty();
    }
};

Calendar.dayMouseOver = function (ev) {
    var el = Calendar.getElement(ev);
    if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
        return false;
    }
    if (el.ttip) {
        if (el.ttip.substr(0, 1) == "_") {
            el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
        }
        el.calendar.tooltips.innerHTML = el.ttip;
    }
    if (el.navtype != 300) {
        Calendar.addClass(el, "hilite");
        if (el.caldate) {
            Calendar.addClass(el.parentNode, "rowhilite");
        }
    }
    return Calendar.stopEvent(ev);
};

Calendar.dayMouseOut = function (ev) {
    with (Calendar) {
        var el = getElement(ev);
        if (isRelated(el, ev) || _C || el.disabled)
            return false;
        removeClass(el, "hilite");
        if (el.caldate)
            removeClass(el.parentNode, "rowhilite");
        if (el.calendar)
            el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
        return stopEvent(ev);
    }
};

/**
*  A generic "click" handler :) handles all types of buttons defined in this
*  calendar.
*/
Calendar.cellClick = function (el, ev) {
    var cal = el.calendar;
    var closing = false;
    var newdate = false;
    var date = null;
    if (typeof el.navtype == "undefined") {
        if (cal.currentDateEl) {
            Calendar.removeClass(cal.currentDateEl, "selected");
            Calendar.addClass(el, "selected");
            closing = (cal.currentDateEl == el);
            if (!closing) {
                cal.currentDateEl = el;
            }
        }
        cal.date.setDateOnly(el.caldate);
        date = cal.date;
        var other_month = !(cal.dateClicked = !el.otherMonth);
        if (!other_month && !cal.currentDateEl)
            cal._toggleMultipleDate(new Date(date));
        else
            newdate = !el.disabled;
        // a date was clicked
        if (other_month)
            cal._init(cal.firstDayOfWeek, date);
    } else {
        if (el.navtype == 200) {
            Calendar.removeClass(el, "hilite");
            cal.callCloseHandler();
            return;
        }
        date = new Date(cal.date);
        if (el.navtype == 0)
            date.setDateOnly(new Date()); // TODAY
        // unless "today" was clicked, we assume no date was clicked so
        // the selected handler will know not to close the calenar when
        // in single-click mode.
        // cal.dateClicked = (el.navtype == 0);
        cal.dateClicked = false;
        var year = date.getFullYear();
        var mon = date.getMonth();
        function setMonth(m) {
            var day = date.getDate();
            var max = date.getMonthDays(m);
            if (day > max) {
                date.setDate(max);
            }
            date.setMonth(m);
        };
        switch (el.navtype) {
            case 400:
                var ppp = cal.params;
                if (ppp.inputField) {
                    ppp.inputField.value = "";
                }
                if (ppp.displayArea)
                    ppp.displayArea.innerHTML = "";
                cal.callCloseHandler();
//                Calendar.removeClass(el, "hilite");
//                var text = Calendar._TT["ABOUT"];
//                if (typeof text != "undefined") {
//                    text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
//                } else {
//                    // FIXME: this should be removed as soon as lang files get updated!
//                    text = "Help and about box text is not translated into this language.\n" +
//					"If you know this language and you feel generous please update\n" +
//					"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
//					"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution  ;-)\n\n" +
//					"Thank you!\n" +
//					"http://dynarch.com/mishoo/calendar.epl\n";
//                }
//                alert(text);
                return;
            case -2:
                if (year > cal.minYear) {
                    date.setFullYear(year - 1);
                }
                break;
            case -1:
                if (mon > 0) {
                    setMonth(mon - 1);
                } else if (year-- > cal.minYear) {
                    date.setFullYear(year);
                    setMonth(11);
                }
                break;
            case 1:
                if (mon < 11) {
                    setMonth(mon + 1);
                } else if (year < cal.maxYear) {
                    date.setFullYear(year + 1);
                    setMonth(0);
                }
                break;
            case 2:
                if (year < cal.maxYear) {
                    date.setFullYear(year + 1);
                }
                break;
            case 100:
                cal.setFirstDayOfWeek(el.fdow);
                return;
            case 50:
                var range = el._range;
                var current = el.innerHTML;
                for (var i = range.length; --i >= 0; )
                    if (range[i] == current)
                        break;
                if (ev && ev.shiftKey) {
                    if (--i < 0)
                        i = range.length - 1;
                } else if (++i >= range.length)
                    i = 0;
                var newval = range[i];
                el.innerHTML = newval;
                cal.onUpdateTime();
                return;
            case 0:
                // TODAY will bring us here
                if ((typeof cal.getDateStatus == "function") &&
			    cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
                    return false;
                }
                break;
        }
        if (!date.equalsTo(cal.date)) {
            cal.setDate(date);
            newdate = true;
        } else if (el.navtype == 0)
            newdate = closing = true;
    }
    if (newdate) {
        ev && cal.callHandler();
    }
    if (closing) {
        Calendar.removeClass(el, "hilite");
        ev && cal.callCloseHandler();
    }
};

// END: CALENDAR STATIC FUNCTIONS

// BEGIN: CALENDAR OBJECT FUNCTIONS

/**
*  This function creates the calendar inside the given parent.  If _par is
*  null than it creates a popup calendar inside the BODY element.  If _par is
*  an element, be it BODY, then it creates a non-popup calendar (still
*  hidden).  Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
    var parent = null;
    if (!_par) {
        // default parent is the document body, in which case we create
        // a popup calendar.
        parent = document.getElementsByTagName("body")[0];
        this.isPopup = true;
    } else {
        parent = _par;
        this.isPopup = false;
    }
    this.date = this.dateStr ? new Date(this.dateStr) : new Date();

    var table = Calendar.createElement("table");
    this.table = table;
    table.cellSpacing = 0;
    table.cellPadding = 0;
    table.calendar = this;
    Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);

    var div = Calendar.createElement("div");
    this.element = div;
    div.className = "calendar";
    if (this.isPopup) {
        div.style.position = "absolute";
        div.style.display = "none";
    }
    div.appendChild(table);

    var thead = Calendar.createElement("thead", table);
    var cell = null;
    var row = null;

    var cal = this;
    var hh = function (text, cs, navtype) {
        cell = Calendar.createElement("td", row);
        cell.colSpan = cs;
        cell.className = "button";
        if (navtype != 0 && Math.abs(navtype) <= 2)
            cell.className += " nav";
        Calendar._add_evs(cell);
        cell.calendar = cal;
        cell.navtype = navtype;
        cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
        return cell;
    };

    row = Calendar.createElement("tr", thead);
    var title_length = 6;
    (this.isPopup) && --title_length;
    (this.weekNumbers) && ++title_length;

    hh("DEL", 1, 400).ttip = Calendar._TT["INFO"];
    this.title = hh("", title_length, 300);
    this.title.className = "title";
    if (this.isPopup) {
        this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
        this.title.style.cursor = "move";
        hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
    }

    row = Calendar.createElement("tr", thead);
    row.className = "headrow";

    this._nav_py = hh("&#x00ab;", 1, -2);
    this._nav_py.ttip = Calendar._TT["PREV_YEAR"];

    this._nav_pm = hh("&#x2039;", 1, -1);
    this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];

    this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
    this._nav_now.ttip = Calendar._TT["GO_TODAY"];

    this._nav_nm = hh("&#x203a;", 1, 1);
    this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];

    this._nav_ny = hh("&#x00bb;", 1, 2);
    this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];

    // day names
    row = Calendar.createElement("tr", thead);
    row.className = "daynames";
    if (this.weekNumbers) {
        cell = Calendar.createElement("td", row);
        cell.className = "name wn";
        cell.innerHTML = Calendar._TT["WK"];
    }
    for (var i = 7; i > 0; --i) {
        cell = Calendar.createElement("td", row);
        if (!i) {
            cell.navtype = 100;
            cell.calendar = this;
            Calendar._add_evs(cell);
        }
    }
    this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
    this._displayWeekdays();

    var tbody = Calendar.createElement("tbody", table);
    this.tbody = tbody;

    for (i = 6; i > 0; --i) {
        row = Calendar.createElement("tr", tbody);
        if (this.weekNumbers) {
            cell = Calendar.createElement("td", row);
        }
        for (var j = 7; j > 0; --j) {
            cell = Calendar.createElement("td", row);
            cell.calendar = this;
            Calendar._add_evs(cell);
        }
    }

    if (this.showsTime) {
        row = Calendar.createElement("tr", tbody);
        row.className = "time";

        cell = Calendar.createElement("td", row);
        cell.className = "time";
        cell.colSpan = 2;
        cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";

        cell = Calendar.createElement("td", row);
        cell.className = "time";
        cell.colSpan = this.weekNumbers ? 4 : 3;

        (function () {
            function makeTimePart(className, init, range_start, range_end) {
                var part = Calendar.createElement("span", cell);
                part.className = className;
                part.innerHTML = init;
                part.calendar = cal;
                part.ttip = Calendar._TT["TIME_PART"];
                part.navtype = 50;
                part._range = [];
                if (typeof range_start != "number")
                    part._range = range_start;
                else {
                    for (var i = range_start; i <= range_end; ++i) {
                        var txt;
                        if (i < 10 && range_end >= 10) txt = '0' + i;
                        else txt = '' + i;
                        part._range[part._range.length] = txt;
                    }
                }
                Calendar._add_evs(part);
                return part;
            };
            var hrs = cal.date.getHours();
            var mins = cal.date.getMinutes();
            var t12 = !cal.time24;
            var pm = (hrs > 12);
            if (t12 && pm) hrs -= 12;
            var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
            var span = Calendar.createElement("span", cell);
            span.innerHTML = ":";
            span.className = "colon";
            var M = makeTimePart("minute", mins, 0, 59);
            var AP = null;
            cell = Calendar.createElement("td", row);
            cell.className = "time";
            cell.colSpan = 2;
            if (t12)
                AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
            else
                cell.innerHTML = "&nbsp;";

            cal.onSetTime = function () {
                var pm, hrs = this.date.getHours(),
					mins = this.date.getMinutes();
                if (t12) {
                    pm = (hrs >= 12);
                    if (pm) hrs -= 12;
                    if (hrs == 0) hrs = 12;
                    AP.innerHTML = pm ? "pm" : "am";
                }
                H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
                M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
            };

            cal.onUpdateTime = function () {
                var date = this.date;
                var h = parseInt(H.innerHTML, 10);
                if (t12) {
                    if (/pm/i.test(AP.innerHTML) && h < 12)
                        h += 12;
                    else if (/am/i.test(AP.innerHTML) && h == 12)
                        h = 0;
                }
                var d = date.getDate();
                var m = date.getMonth();
                var y = date.getFullYear();
                date.setHours(h);
                date.setMinutes(parseInt(M.innerHTML, 10));
                date.setFullYear(y);
                date.setMonth(m);
                date.setDate(d);
                this.dateClicked = false;
                this.callHandler();
            };
        })();
    } else {
        this.onSetTime = this.onUpdateTime = function () { };
    }

    var tfoot = Calendar.createElement("tfoot", table);

    row = Calendar.createElement("tr", tfoot);
    row.className = "footrow";

    cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
    cell.className = "ttip";
    if (this.isPopup) {
        cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
        cell.style.cursor = "move";
    }
    this.tooltips = cell;

    div = Calendar.createElement("div", this.element);
    this.monthsCombo = div;
    div.className = "combo";
    for (i = 0; i < Calendar._MN.length; ++i) {
        var mn = Calendar.createElement("div");
        mn.className = Calendar.is_ie ? "label-IEfix" : "label";
        mn.month = i;
        mn.innerHTML = Calendar._SMN[i];
        div.appendChild(mn);
    }

    div = Calendar.createElement("div", this.element);
    this.yearsCombo = div;
    div.className = "combo";
    for (i = 12; i > 0; --i) {
        var yr = Calendar.createElement("div");
        yr.className = Calendar.is_ie ? "label-IEfix" : "label";
        div.appendChild(yr);
    }

    this._init(this.firstDayOfWeek, this.date);
    parent.appendChild(this.element);
};

/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function (ev) {
    var cal = window._dynarch_popupCalendar;
    if (!cal || cal.multiple)
        return false;
    (Calendar.is_ie) && (ev = window.event);
    var act = (Calendar.is_ie || ev.type == "keypress"),
		K = ev.keyCode;
    if (ev.ctrlKey) {
        switch (K) {
            case 37: // KEY left
                act && Calendar.cellClick(cal._nav_pm);
                break;
            case 38: // KEY up
                act && Calendar.cellClick(cal._nav_py);
                break;
            case 39: // KEY right
                act && Calendar.cellClick(cal._nav_nm);
                break;
            case 40: // KEY down
                act && Calendar.cellClick(cal._nav_ny);
                break;
            default:
                return false;
        }
    } else switch (K) {
        case 32: // KEY space (now)
            Calendar.cellClick(cal._nav_now);
            break;
        case 27: // KEY esc
            act && cal.callCloseHandler();
            break;
        case 37: // KEY left
        case 38: // KEY up
        case 39: // KEY right
        case 40: // KEY down
            if (act) {
                var prev, x, y, ne, el, step;
                prev = K == 37 || K == 38;
                step = (K == 37 || K == 39) ? 1 : 7;
                function setVars() {
                    el = cal.currentDateEl;
                    var p = el.pos;
                    x = p & 15;
                    y = p >> 4;
                    ne = cal.ar_days[y][x];
                }; setVars();
                function prevMonth() {
                    var date = new Date(cal.date);
                    date.setDate(date.getDate() - step);
                    cal.setDate(date);
                };
                function nextMonth() {
                    var date = new Date(cal.date);
                    date.setDate(date.getDate() + step);
                    cal.setDate(date);
                };
                while (1) {
                    switch (K) {
                        case 37: // KEY left
                            if (--x >= 0)
                                ne = cal.ar_days[y][x];
                            else {
                                x = 6;
                                K = 38;
                                continue;
                            }
                            break;
                        case 38: // KEY up
                            if (--y >= 0)
                                ne = cal.ar_days[y][x];
                            else {
                                prevMonth();
                                setVars();
                            }
                            break;
                        case 39: // KEY right
                            if (++x < 7)
                                ne = cal.ar_days[y][x];
                            else {
                                x = 0;
                                K = 40;
                                continue;
                            }
                            break;
                        case 40: // KEY down
                            if (++y < cal.ar_days.length)
                                ne = cal.ar_days[y][x];
                            else {
                                nextMonth();
                                setVars();
                            }
                            break;
                    }
                    break;
                }
                if (ne) {
                    if (!ne.disabled)
                        Calendar.cellClick(ne);
                    else if (prev)
                        prevMonth();
                    else
                        nextMonth();
                }
            }
            break;
        case 13: // KEY enter
            if (act)
                Calendar.cellClick(cal.currentDateEl, ev);
            break;
        default:
            return false;
    }
    return Calendar.stopEvent(ev);
};

/**
*  (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
Calendar.prototype._init = function (firstDayOfWeek, date) {
    var today = new Date(),
		TY = today.getFullYear(),
		TM = today.getMonth(),
		TD = today.getDate();
    this.table.style.visibility = "hidden";
    var year = date.getFullYear();
    if (year < this.minYear) {
        year = this.minYear;
        date.setFullYear(year);
    } else if (year > this.maxYear) {
        year = this.maxYear;
        date.setFullYear(year);
    }
    this.firstDayOfWeek = firstDayOfWeek;
    this.date = new Date(date);
    var month = date.getMonth();
    var mday = date.getDate();
    var no_days = date.getMonthDays();

    // calendar voodoo for computing the first day that would actually be
    // displayed in the calendar, even if it's from the previous month.
    // WARNING: this is magic. ;-)
    date.setDate(1);
    var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
    if (day1 < 0)
        day1 += 7;
    date.setDate(-day1);
    date.setDate(date.getDate() + 1);

    var row = this.tbody.firstChild;
    var MN = Calendar._SMN[month];
    var ar_days = this.ar_days = new Array();
    var weekend = Calendar._TT["WEEKEND"];
    var dates = this.multiple ? (this.datesCells = {}) : null;
    for (var i = 0; i < 6; ++i, row = row.nextSibling) {
        var cell = row.firstChild;
        if (this.weekNumbers) {
            cell.className = "day wn";
            cell.innerHTML = date.getWeekNumber();
            cell = cell.nextSibling;
        }
        row.className = "daysrow";
        var hasdays = false, iday, dpos = ar_days[i] = [];
        for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
            iday = date.getDate();
            var wday = date.getDay();
            cell.className = "day";
            cell.pos = i << 4 | j;
            dpos[j] = cell;
            var current_month = (date.getMonth() == month);
            if (!current_month) {
                if (this.showsOtherMonths) {
                    cell.className += " othermonth";
                    cell.otherMonth = true;
                } else {
                    cell.className = "emptycell";
                    cell.innerHTML = "&nbsp;";
                    cell.disabled = true;
                    continue;
                }
            } else {
                cell.otherMonth = false;
                hasdays = true;
            }
            cell.disabled = false;
            cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
            if (dates)
                dates[date.print("%Y%m%d")] = cell;
            if (this.getDateStatus) {
                var status = this.getDateStatus(date, year, month, iday);
                if (this.getDateToolTip) {
                    var toolTip = this.getDateToolTip(date, year, month, iday);
                    if (toolTip)
                        cell.title = toolTip;
                }
                if (status === true) {
                    cell.className += " disabled";
                    cell.disabled = true;
                } else {
                    if (/disabled/i.test(status))
                        cell.disabled = true;
                    cell.className += " " + status;
                }
            }
            if (!cell.disabled) {
                cell.caldate = new Date(date);
                cell.ttip = "_";
                if (!this.multiple && current_month
				    && iday == mday && this.hiliteToday) {
                    cell.className += " selected";
                    this.currentDateEl = cell;
                }
                if (date.getFullYear() == TY &&
				    date.getMonth() == TM &&
				    iday == TD) {
                    cell.className += " today";
                    cell.ttip += Calendar._TT["PART_TODAY"];
                }
                if (weekend.indexOf(wday.toString()) != -1)
                    cell.className += cell.otherMonth ? " oweekend" : " weekend";
            }
        }
        if (!(hasdays || this.showsOtherMonths))
            row.className = "emptyrow";
    }
    this.title.innerHTML = Calendar._MN[month] + ", " + year;
    this.onSetTime();
    this.table.style.visibility = "visible";
    this._initMultipleDates();
    // PROFILE
    // this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};

Calendar.prototype._initMultipleDates = function () {
    if (this.multiple) {
        for (var i in this.multiple) {
            var cell = this.datesCells[i];
            var d = this.multiple[i];
            if (!d)
                continue;
            if (cell)
                cell.className += " selected";
        }
    }
};

Calendar.prototype._toggleMultipleDate = function (date) {
    if (this.multiple) {
        var ds = date.print("%Y%m%d");
        var cell = this.datesCells[ds];
        if (cell) {
            var d = this.multiple[ds];
            if (!d) {
                Calendar.addClass(cell, "selected");
                this.multiple[ds] = date;
            } else {
                Calendar.removeClass(cell, "selected");
                delete this.multiple[ds];
            }
        }
    }
};

Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
    this.getDateToolTip = unaryFunction;
};

/**
*  Calls _init function above for going to a certain date (but only if the
*  date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
    if (!date.equalsTo(this.date)) {
        this._init(this.firstDayOfWeek, date);
    }
};

/**
*  Refreshes the calendar.  Useful if the "disabledHandler" function is
*  dynamic, meaning that the list of disabled date can change at runtime.
*  Just * call this function if you think that the list of disabled dates
*  should * change.
*/
Calendar.prototype.refresh = function () {
    this._init(this.firstDayOfWeek, this.date);
};

/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
    this._init(firstDayOfWeek, this.date);
    this._displayWeekdays();
};

/**
*  Allows customization of what dates are enabled.  The "unaryFunction"
*  parameter must be a function object that receives the date (as a JS Date
*  object) and returns a boolean value.  If the returned value is true then
*  the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
    this.getDateStatus = unaryFunction;
};

/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
    this.minYear = a;
    this.maxYear = z;
};

/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
    if (this.onSelected) {
        this.onSelected(this, this.date.print(this.dateFormat));
    }
};

/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
    if (this.onClose) {
        this.onClose(this);
    }
    this.hideShowCovered();
};

/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
    var el = this.element.parentNode;
    el.removeChild(this.element);
    Calendar._C = null;
    window._dynarch_popupCalendar = null;
};

/**
*  Moves the calendar element to a different section in the DOM tree (changes
*  its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
    var el = this.element;
    el.parentNode.removeChild(el);
    new_parent.appendChild(el);
};

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function (ev) {
    var calendar = window._dynarch_popupCalendar;
    if (!calendar) {
        return false;
    }
    var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
    for (; el != null && el != calendar.element; el = el.parentNode);
    if (el == null) {
        // calls closeHandler which should hide the calendar.
        window._dynarch_popupCalendar.callCloseHandler();
        return Calendar.stopEvent(ev);
    }
};

/** Shows the calendar. */
Calendar.prototype.show = function () {
    var rows = this.table.getElementsByTagName("tr");
    for (var i = rows.length; i > 0; ) {
        var row = rows[--i];
        Calendar.removeClass(row, "rowhilite");
        var cells = row.getElementsByTagName("td");
        for (var j = cells.length; j > 0; ) {
            var cell = cells[--j];
            Calendar.removeClass(cell, "hilite");
            Calendar.removeClass(cell, "active");
        }
    }
    this.element.style.display = "block";
    this.element.style.zIndex = 99999999999999;
    this.hidden = false;
    if (this.isPopup) {
        window._dynarch_popupCalendar = this;
        Calendar.addEvent(document, "keydown", Calendar._keyEvent);
        Calendar.addEvent(document, "keypress", Calendar._keyEvent);
        Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
    }
    this.hideShowCovered();
};

/**
*  Hides the calendar.  Also removes any "hilite" from the class of any TD
*  element.
*/
Calendar.prototype.hide = function () {
    if (this.isPopup) {
        Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
        Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
        Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
    }
    this.element.style.display = "none";
    this.hidden = true;
    this.hideShowCovered();
};

/**
*  Shows the calendar at a given absolute position (beware that, depending on
*  the calendar element style -- position property -- this might be relative
*  to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
    var s = this.element.style;
    s.left = x + "px";
    s.top = y + "px";
    this.show();
};

/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
    var self = this;
    var p = Calendar.getAbsolutePos(el);
    if (!opts || typeof opts != "string") {
        this.showAt(p.x, p.y + el.offsetHeight);
        return true;
    }
    function fixPosition(box) {
        if (box.x < 0)
            box.x = 0;
        if (box.y < 0)
            box.y = 0;
        var cp = document.createElement("div");
        var s = cp.style;
        s.position = "absolute";
        s.right = s.bottom = s.width = s.height = "0px";
        document.body.appendChild(cp);
        var br = Calendar.getAbsolutePos(cp);
        document.body.removeChild(cp);
        if (Calendar.is_ie) {
            br.y += $(document).scrollTop();
            br.x += $(document).scrollLeft();
        } else {
            br.y += window.scrollY;
            br.x += window.scrollX;
        }
        var tmp = box.x + box.width - br.x;
        if (tmp > 0) box.x -= tmp;
        tmp = box.y + box.height - br.y;
        if (tmp > 0) box.y -= tmp;
    };
    this.element.style.display = "block";
    Calendar.continuation_for_the_fucking_khtml_browser = function () {
        var w = self.element.offsetWidth;
        var h = self.element.offsetHeight;
        self.element.style.display = "none";
        var valign = opts.substr(0, 1);
        var halign = "l";
        if (opts.length > 1) {
            halign = opts.substr(1, 1);
        }
        // vertical alignment
        switch (valign) {
            case "T": p.y -= h; break;
            case "B": p.y += el.offsetHeight; break;
            case "C": p.y += (el.offsetHeight - h) / 2; break;
            case "t": p.y += el.offsetHeight - h; break;
            case "b": break; // already there
        }
        // horizontal alignment
        switch (halign) {
            case "L": p.x -= w; break;
            case "R": p.x += el.offsetWidth; break;
            case "C": p.x += (el.offsetWidth - w) / 2; break;
            case "l": p.x += el.offsetWidth - w; break;
            case "r": break; // already there
        }
        p.width = w;
        p.height = h + 40;
        self.monthsCombo.style.display = "none";
        fixPosition(p);
        self.showAt(p.x, p.y);
    };
    if (Calendar.is_khtml)
        setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
    else
        Calendar.continuation_for_the_fucking_khtml_browser();
};

/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
    this.dateFormat = str;
};

/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
    this.ttDateFormat = str;
};

/**
*  Tries to identify the date represented in a string.  If successful it also
*  calls this.setDate which moves the calendar to the given date.
*/
Calendar.prototype.parseDate = function (str, fmt) {
    if (!fmt)
        fmt = this.dateFormat;
    this.setDate(Date.parseDate(str, fmt));
};

Calendar.prototype.hideShowCovered = function () {
    if (!Calendar.is_ie && !Calendar.is_opera)
        return;
    function getVisib(obj) {
        var value = obj.style.visibility;
        if (!value) {
            if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
                if (!Calendar.is_khtml)
                    value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
                else
                    value = '';
            } else if (obj.currentStyle) { // IE
                value = obj.currentStyle.visibility;
            } else
                value = '';
        }
        return value;
    };

    var tags = new Array("applet", "iframe", "select");
    var el = this.element;

    var p = Calendar.getAbsolutePos(el);
    var EX1 = p.x;
    var EX2 = el.offsetWidth + EX1;
    var EY1 = p.y;
    var EY2 = el.offsetHeight + EY1;

    for (var k = tags.length; k > 0; ) {
        var ar = document.getElementsByTagName(tags[--k]);
        var cc = null;

        for (var i = ar.length; i > 0; ) {
            cc = ar[--i];

            p = Calendar.getAbsolutePos(cc);
            var CX1 = p.x;
            var CX2 = cc.offsetWidth + CX1;
            var CY1 = p.y;
            var CY2 = cc.offsetHeight + CY1;

            if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
                if (!cc.__msh_save_visibility) {
                    cc.__msh_save_visibility = getVisib(cc);
                }
                cc.style.visibility = cc.__msh_save_visibility;
            } else {
                if (!cc.__msh_save_visibility) {
                    cc.__msh_save_visibility = getVisib(cc);
                }
                cc.style.visibility = "hidden";
            }
        }
    }
};

/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
    var fdow = this.firstDayOfWeek;
    var cell = this.firstdayname;
    var weekend = Calendar._TT["WEEKEND"];
    for (var i = 0; i < 7; ++i) {
        cell.className = "day name";
        var realday = (i + fdow) % 7;
        if (i) {
            cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
            cell.navtype = 100;
            cell.calendar = this;
            cell.fdow = realday;
            Calendar._add_evs(cell);
        }
        if (weekend.indexOf(realday.toString()) != -1) {
            Calendar.addClass(cell, "weekend");
        }
        cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
        cell = cell.nextSibling;
    }
};

/** Internal function.  Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
    this.monthsCombo.style.display = "none";
    this.yearsCombo.style.display = "none";
};

/** Internal function.  Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
    if (this.dragging) {
        return;
    }
    this.dragging = true;
    var posX;
    var posY;
    if (Calendar.is_ie) {
        posY = window.event.clientY + $(document).scrollTop();
        posX = window.event.clientX + $(document).scrollLeft();
    } else {
        posY = ev.clientY + window.scrollY;
        posX = ev.clientX + window.scrollX;
    }
    var st = this.element.style;
    this.xOffs = posX - parseInt(st.left);
    this.yOffs = posY - parseInt(st.top);
    with (Calendar) {
        addEvent(document, "mousemove", calDragIt);
        addEvent(document, "mouseup", calDragEnd);
    }
};

// BEGIN: DATE OBJECT PATCHES

/** Adds the number of days array to the Date object. */
Date._MD = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;

Date.parseDate = function (str, fmt) {
    var today = new Date();
    var y = 0;
    var m = -1;
    var d = 0;
    var a = str.split(/\W+/);
    var b = fmt.match(/%./g);
    var i = 0, j = 0;
    var hr = 0;
    var min = 0;
    for (i = 0; i < a.length; ++i) {
        if (!a[i])
            continue;
        switch (b[i]) {
            case "%d":
            case "%e":
                d = parseInt(a[i], 10);
                break;

            case "%m":
                m = parseInt(a[i], 10) - 1;
                break;

            case "%Y":
            case "%y":
                y = parseInt(a[i], 10);
                (y < 100) && (y += (y > 29) ? 1900 : 2000);
                break;

            case "%b":
            case "%B":
                for (j = 0; j < 12; ++j) {
                    if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
                }
                break;

            case "%H":
            case "%I":
            case "%k":
            case "%l":
                hr = parseInt(a[i], 10);
                break;

            case "%P":
            case "%p":
                if (/pm/i.test(a[i]) && hr < 12)
                    hr += 12;
                else if (/am/i.test(a[i]) && hr >= 12)
                    hr -= 12;
                break;

            case "%M":
                min = parseInt(a[i], 10);
                break;
        }
    }
    if (isNaN(y)) y = today.getFullYear();
    if (isNaN(m)) m = today.getMonth();
    if (isNaN(d)) d = today.getDate();
    if (isNaN(hr)) hr = today.getHours();
    if (isNaN(min)) min = today.getMinutes();
    if (y != 0 && m != -1 && d != 0)
        return new Date(y, m, d, hr, min, 0);
    y = 0; m = -1; d = 0;
    for (i = 0; i < a.length; ++i) {
        if (a[i].search(/[a-zA-Z]+/) != -1) {
            var t = -1;
            for (j = 0; j < 12; ++j) {
                if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
            }
            if (t != -1) {
                if (m != -1) {
                    d = m + 1;
                }
                m = t;
            }
        } else if (parseInt(a[i], 10) <= 12 && m == -1) {
            m = a[i] - 1;
        } else if (parseInt(a[i], 10) > 31 && y == 0) {
            y = parseInt(a[i], 10);
            (y < 100) && (y += (y > 29) ? 1900 : 2000);
        } else if (d == 0) {
            d = a[i];
        }
    }
    if (y == 0)
        y = today.getFullYear();
    if (m != -1 && d != 0)
        return new Date(y, m, d, hr, min, 0);
    return today;
};

/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function (month) {
    var year = this.getFullYear();
    if (typeof month == "undefined") {
        month = this.getMonth();
    }
    if (((0 == (year % 4)) && ((0 != (year % 100)) || (0 == (year % 400)))) && month == 1) {
        return 29;
    } else {
        return Date._MD[month];
    }
};

/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function () {
    var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
    var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
    var time = now - then;
    return Math.floor(time / Date.DAY);
};

/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function () {
    var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
    var DoW = d.getDay();
    d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
    var ms = d.valueOf(); // GMT
    d.setMonth(0);
    d.setDate(4); // Thu in Week 1
    return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

/** Checks date and time equality */
Date.prototype.equalsTo = function (date) {
    return ((this.getFullYear() == date.getFullYear()) &&
		(this.getMonth() == date.getMonth()) &&
		(this.getDate() == date.getDate()) &&
		(this.getHours() == date.getHours()) &&
		(this.getMinutes() == date.getMinutes()));
};

/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function (date) {
    var tmp = new Date(date);
    this.setDate(1);
    this.setFullYear(tmp.getFullYear());
    this.setMonth(tmp.getMonth());
    this.setDate(tmp.getDate());
};

/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
    var m = this.getMonth();
    var d = this.getDate();
    var y = this.getFullYear();
    var wn = this.getWeekNumber();
    var w = this.getDay();
    var s = {};
    var hr = this.getHours();
    var pm = (hr >= 12);
    var ir = (pm) ? (hr - 12) : hr;
    var dy = this.getDayOfYear();
    if (ir == 0)
        ir = 12;
    var min = this.getMinutes();
    var sec = this.getSeconds();
    s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
    s["%A"] = Calendar._DN[w]; // full weekday name
    s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
    s["%B"] = Calendar._MN[m]; // full month name
    // FIXME: %c : preferred date and time representation for the current locale
    s["%C"] = 1 + Math.floor(y / 100); // the century number
    s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
    s["%e"] = d; // the day of the month (range 1 to 31)
    // FIXME: %D : american date style: %m/%d/%y
    // FIXME: %E, %F, %G, %g, %h (man strftime)
    s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
    s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
    s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
    s["%k"] = hr; 	// hour, range 0 to 23 (24h format)
    s["%l"] = ir; 	// hour, range 1 to 12 (12h format)
    s["%m"] = (m < 9) ? ("0" + (1 + m)) : (1 + m); // month, range 01 to 12
    s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
    s["%n"] = "\n"; 	// a newline character
    s["%p"] = pm ? "PM" : "AM";
    s["%P"] = pm ? "pm" : "am";
    // FIXME: %r : the time in am/pm notation %I:%M:%S %p
    // FIXME: %R : the time in 24-hour notation %H:%M
    s["%s"] = Math.floor(this.getTime() / 1000);
    s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
    s["%t"] = "\t"; 	// a tab character
    // FIXME: %T : the time in 24-hour notation (%H:%M:%S)
    s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
    s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
    s["%w"] = w; 	// the day of the week (range 0 to 6, 0 = SUN)
    // FIXME: %x : preferred date representation for the current locale without the time
    // FIXME: %X : preferred time representation for the current locale without the date
    s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
    s["%Y"] = y; 	// year with the century
    s["%%"] = "%"; 	// a literal '%' character

    var re = /%./g;
    if (!Calendar.is_ie5 && !Calendar.is_khtml)
        return str.replace(re, function (par) { return s[par] || par; });

    var a = str.match(re);
    for (var i = 0; i < a.length; i++) {
        var tmp = s[a[i]];
        if (tmp) {
            re = new RegExp(a[i], 'g');
            str = str.replace(re, tmp);
        }
    }

    return str;
};

Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function (y) {
    var d = new Date(this);
    d.__msh_oldSetFullYear(y);
    if (d.getMonth() != this.getMonth())
        this.setDate(28);
    this.__msh_oldSetFullYear(y);
};

// END: DATE OBJECT PATCHES


// global object that remembers the calendar
window._dynarch_popupCalendar = null;


// ** I18N

// Calendar EN language
// Author: Mihai Bazon, <mihai_bazon@yahoo.com>
// Encoding: any
// Distributed under the same terms as the calendar itself.

// For translators: please use UTF-8 if possible.  We strongly believe that
// Unicode is the answer to a real internationalized world.  Also please
// include your contact information in the header, as can be seen above.

// full day names
Calendar._DN = new Array
("Sunday",
 "Monday",
 "Tuesday",
 "Wednesday",
 "Thursday",
 "Friday",
 "Saturday",
 "Sunday");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("Sun",
 "Mon",
 "Tue",
 "Wed",
 "Thu",
 "Fri",
 "Sat",
 "Sun");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;

// full month names
Calendar._MN = new Array
("January",
 "February",
 "March",
 "April",
 "May",
 "June",
 "July",
 "August",
 "September",
 "October",
 "November",
 "December");

// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "May",
 "Jun",
 "Jul",
 "Aug",
 "Sep",
 "Oct",
 "Nov",
 "Dec");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (today)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Time:";



/*  Copyright Mihai Bazon, 2002, 2003  |  http://dynarch.com/mishoo/
* ---------------------------------------------------------------------------
*
* The DHTML Calendar
*
* Details and latest version at:
* http://dynarch.com/mishoo/calendar.epl
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*
* This file defines helper functions for setting up the calendar.  They are
* intended to help non-programmers get a working calendar on their site
* quickly.  This script should not be seen as part of the calendar.  It just
* shows you what one can do with the calendar, while in the same time
* providing a quick and simple method for setting it up.  If you need
* exhaustive customization of the calendar creation process feel free to
* modify this code to suit your needs (this is recommended and much better
* than modifying calendar.js itself).
*/

// $Id: calendar-setup.js,v 1.25 2005/03/07 09:51:33 mishoo Exp $

/**
*  This function "patches" an input field (or other element) to use a calendar
*  widget for date selection.
*
*  The "params" is a single object that can have the following properties:
*
*    prop. name   | description
*  -------------------------------------------------------------------------------------------------
*   inputField    | the ID of an input field to store the date
*   displayArea   | the ID of a DIV or other element to show the date
*   button        | ID of a button or other element that will trigger the calendar
*   eventName     | event that will trigger the calendar, without the "on" prefix (default: "click")
*   ifFormat      | date format that will be stored in the input field
*   daFormat      | the date format that will be used to display the date in displayArea
*   singleClick   | (true/false) wether the calendar is in single click mode or not (default: true)
*   firstDay      | numeric: 0 to 6.  "0" means display Sunday first, "1" means display Monday first, etc.
*   align         | alignment (default: "Br"); if you don't know what's this see the calendar documentation
*   range         | array with 2 elements.  Default: [1900, 2999] -- the range of years available
*   weekNumbers   | (true/false) if it's true (default) the calendar will display week numbers
*   flat          | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
*   flatCallback  | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
*   disableFunc   | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
*   onSelect      | function that gets called when a date is selected.  You don't _have_ to supply this (the default is generally okay)
*   onClose       | function that gets called when the calendar is closed.  [default]
*   onUpdate      | function that gets called after the date is updated in the input field.  Receives a reference to the calendar.
*   date          | the date that the calendar will be initially displayed to
*   showsTime     | default: false; if true the calendar will include a time selector
*   timeFormat    | the time format; can be "12" or "24", default is "12"
*   electric      | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
*   step          | configures the step of the years in drop-down boxes; default: 2
*   position      | configures the calendar absolute position; default: null
*   cache         | if "true" (but default: "false") it will reuse the same calendar object, where possible
*   showOthers    | if "true" (but default: "false") it will show days from other months too
*
*  None of them is required, they all have default values.  However, if you
*  pass none of "inputField", "displayArea" or "button" you'll get a warning
*  saying "nothing to setup".
*/
Calendar.setup = function (params) {
    function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

    param_default("inputField", null);
    param_default("displayArea", null);
    param_default("button", null);
    param_default("eventName", "click");
    param_default("ifFormat", "%Y/%m/%d");
    param_default("daFormat", "%Y/%m/%d");
    param_default("singleClick", true);
    param_default("disableFunc", null);
    param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
    param_default("dateText", null);
    param_default("firstDay", null);
    param_default("align", "Br");
    param_default("range", [1900, 2999]);
    param_default("weekNumbers", true);
    param_default("flat", null);
    param_default("flatCallback", null);
    param_default("onSelect", null);
    param_default("onClose", null);
    param_default("onUpdate", null);
    param_default("date", null);
    param_default("showsTime", true);
    param_default("timeFormat", "24");
    param_default("electric", true);
    param_default("step", 2);
    param_default("position", null);
    param_default("cache", false);
    param_default("showOthers", false);
    param_default("multiple", null);

    /*
    var tmp = ["inputField", "displayArea", "button"];
    for (var i in tmp) {
    if (typeof params[tmp[i]] == "string") {
    params[tmp[i]] = document.getElementById(params[tmp[i]]);
    }
    }
    if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
    alert("Calendar.setup:\n  Nothing to setup (no fields found).  Please check your code");
    return false;
    }
    */
    function onSelect(cal) {
        var p = cal.params;
        var update = (cal.dateClicked || p.electric);
        if (update && p.inputField) {
            p.inputField.value = cal.date.print(p.ifFormat);
            if (typeof p.inputField.onchange == "function")
                p.inputField.onchange();
        }
        if (update && p.displayArea)
            p.displayArea.innerHTML = cal.date.print(p.daFormat);
        if (update && typeof p.onUpdate == "function")
            p.onUpdate(cal);
        if (update && p.flat) {
            if (typeof p.flatCallback == "function")
                p.flatCallback(cal);
        }
        if (update && p.singleClick && cal.dateClicked)
            cal.callCloseHandler();
    };

    if (params.flat != null) {
        if (typeof params.flat == "string")
            params.flat = document.getElementById(params.flat);
        if (!params.flat) {
            alert("Calendar.setup:\n  Flat specified but can't find parent.");
            return false;
        }
        var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
        cal.showsOtherMonths = params.showOthers;
        cal.showsTime = params.showsTime;
        cal.time24 = (params.timeFormat == "24");
        cal.params = params;
        cal.weekNumbers = params.weekNumbers;
        cal.setRange(params.range[0], params.range[1]);
        cal.setDateStatusHandler(params.dateStatusFunc);
        cal.getDateText = params.dateText;
        if (params.ifFormat) {
            cal.setDateFormat(params.ifFormat);
        }
        if (params.inputField && typeof params.inputField.value == "string") {
            cal.parseDate(params.inputField.value);
        }
        cal.create(params.flat);
        cal.show();
        return false;
    }

    var triggerEl = params.button || params.displayArea || params.inputField;
    triggerEl["on" + params.eventName] = Calendar.trigger(params);
    return cal;
};

Calendar.trigger = function (params) {
    function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

    param_default("inputField", null);
    param_default("displayArea", null);
    param_default("button", null);
    param_default("eventName", "click");
    param_default("ifFormat", "%Y/%m/%d");
    param_default("daFormat", "%Y/%m/%d");
    param_default("singleClick", true);
    param_default("disableFunc", null);
    param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined
    param_default("dateText", null);
    param_default("firstDay", null);
    param_default("align", "Br");
    param_default("range", [1900, 2999]);
    param_default("weekNumbers", true);
    param_default("flat", null);
    param_default("flatCallback", null);
    param_default("onSelect", null);
    param_default("onClose", null);
    param_default("onUpdate", null);
    param_default("date", null);
    param_default("showsTime", true);
    param_default("timeFormat", "24");
    param_default("electric", true);
    param_default("step", 2);
    param_default("position", null);
    param_default("cache", true);
    param_default("showOthers", false);
    param_default("multiple", null);

    var tmp = ["inputField", "displayArea", "button"];
    for (var i in tmp) {
        if (typeof params[tmp[i]] == "string") {
            params[tmp[i]] = document.getElementById(params[tmp[i]]);
        }
    }

    function onSelect(cal) {
        var p = cal.params;
        var update = (cal.dateClicked || p.electric);
        if (update && p.inputField) {
            p.inputField.value = cal.date.print(p.ifFormat);
            if (typeof p.inputField.onchange == "function")
                p.inputField.onchange();
        }
        if (update && p.displayArea)
            p.displayArea.innerHTML = cal.date.print(p.daFormat);
        if (update && typeof p.onUpdate == "function")
            p.onUpdate(cal);
        if (update && p.flat) {
            if (typeof p.flatCallback == "function")
                p.flatCallback(cal);
        }
        if (update && p.singleClick && cal.dateClicked)
            cal.callCloseHandler();
    };

    var dateEl = params.inputField || params.displayArea;



    var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
    var mustCreate = false;
    var cal = window.calendar;
    if (dateEl) {
        params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
    }
    if (!(cal && params.cache)) {
        window.calendar = cal = new Calendar(params.firstDay,
							     params.date,
							     params.onSelect || onSelect,
							     params.onClose || function (cal) { cal.hide(); });
        cal.showsTime = params.showsTime;
        cal.time24 = (params.timeFormat == "24");
        cal.weekNumbers = params.weekNumbers;
        mustCreate = true;
    } else {
        if (params.date)
            cal.setDate(params.date);
        cal.hide();
    }
    if (params.multiple) {
        cal.multiple = {};
        for (var i = params.multiple.length; --i >= 0; ) {
            var d = params.multiple[i];
            var ds = d.print("%Y%m%d");
            cal.multiple[ds] = d;
        }
    }
    cal.showsOtherMonths = params.showOthers;
    cal.yearStep = params.step;
    cal.setRange(params.range[0], params.range[1]);
    cal.params = params;
    cal.setDateStatusHandler(params.dateStatusFunc);
    cal.getDateText = params.dateText;
    cal.setDateFormat(dateFmt);

    cal.inputField = params.inputField;

    if (mustCreate)
        cal.create();
    cal.refresh();
    if (!params.position)
        cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
    else
        cal.showAt(params.position[0], params.position[1]);
    return false;
};
// ** I18N

// Calendar ZH language
// Author: muziq, <muziq@sina.com>
// Encoding: GB2312 or GBK
// Distributed under the same terms as the calendar itself.

// full day names
Calendar._DN = new Array
("周日",
 "周一",
 "周二",
 "周三",
 "周四",
 "周五",
 "周六",
 "周日");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("日",
 "一",
 "二",
 "三",
 "四",
 "五",
 "六",
 "日");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;

// full month names
Calendar._MN = new Array
("一月",
 "二月",
 "三月",
 "四月",
 "五月",
 "六月",
 "七月",
 "八月",
 "九月",
 "十月",
 "十一月",
 "十二月");

// short month names
Calendar._SMN = new Array
("一月",
 "二月",
 "三月",
 "四月",
 "五月",
 "六月",
 "七月",
 "八月",
 "九月",
 "十月",
 "十一月",
 "十二月");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "删除日期和时间";

Calendar._TT["ABOUT"] =
"选择日期:\n" +
"- 点击 \xab, \xbb 按钮选择年份\n" +
"- 点击 " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " 按钮选择月份\n" +
"- 长按以上按钮可从菜单中快速选择年份或月份";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"选择时间:\n" +
"- 点击小时或分钟可使改数值加一\n" +
"- 按住Shift键点击小时或分钟可使改数值减一\n" +
"- 点击拖动鼠标可进行快速选择";

Calendar._TT["PREV_YEAR"] = "上一年 (按住出菜单)";
Calendar._TT["PREV_MONTH"] = "上一月 (按住出菜单)";
Calendar._TT["GO_TODAY"] = "转到今日";
Calendar._TT["NEXT_MONTH"] = "下一月 (按住出菜单)";
Calendar._TT["NEXT_YEAR"] = "下一年 (按住出菜单)";
Calendar._TT["SEL_DATE"] = "选择日期";
Calendar._TT["DRAG_TO_MOVE"] = "拖动";
Calendar._TT["PART_TODAY"] = " (今日)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "最左边显示%s";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "关闭";
Calendar._TT["TODAY"] = "今日";
Calendar._TT["TIME_PART"] = "(Shift-)点击鼠标或拖动改变值";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%A, %b %e日";

Calendar._TT["WK"] = "周";
Calendar._TT["TIME"] = "时间:";


$.fn.date_input = function (format) {
    var input = this[0];
    var showCalendar = function () {
        format = format || "%Y-%m-%d %H:%M:%S";
        Calendar.trigger({
            inputField: input, 		// id of the input field
            ifFormat: format,       // format of the input field
            showsTime: true,            // will display a time selector
            button: input.id,   // trigger for the calendar (button ID)
            singleClick: true,
            //            onClose: fillDate,
            step: 1                // show all years in drop-down boxes (instead of every other year as default)
        });
    };
    this.click(function () { if (this.readOnly) { return; } showCalendar(); });
};



//除法函数，用来得到精确的除法结果 
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。 
//调用：accDiv(arg1,arg2) 
//返回值：arg1除以arg2的精确结果
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
    try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""))
        r2 = Number(arg2.toString().replace(".", ""))
        return (r1 / r2) * pow(10, t2 - t1);
    }
};
//给Number类型增加一个div方法，调用起来更加方便。
Number.prototype.div = function (arg) {
    return accDiv(this, arg);
};
//乘法函数，用来得到精确的乘法结果 
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 
//调用：accMul(arg1,arg2) 
//返回值：arg1乘以arg2的精确结果 
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
}
//给Number类型增加一个mul方法，调用起来更加方便。
Number.prototype.mul = function (arg) {
    return accMul(arg, this);
};
//加法函数，用来得到精确的加法结果 
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
//调用：accAdd(arg1,arg2) 
//返回值：arg1加上arg2的精确结果 
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (((arg1 * m).round2(0) + (arg2 * m).round2(0)) / m).round2(Math.max(r1, r2))
};
//给Number类型增加一个add方法，调用起来更加方便。
Number.prototype.add = function (arg) {
    return accAdd(arg, this);
};
//减法函数，用来得到精确的减法结果 
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
//调用：accAdd(arg1,arg2) 
//返回值：arg1加上arg2的精确结果 
function accSub(arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return parseFloat((((arg1 * m).round2(0) - (arg2 * m).round2(0)) / m).toFixed(n));
}
//给Number类型增加一个sub方法，调用起来更加方便。
Number.prototype.sub = function (arg) {
    return accSub(this, arg);
};
function accRound2(number, fractionDigits) {
    with (Math) {
        return parseFloat(round(number * pow(10, fractionDigits)) / pow(10, fractionDigits));
    }
};
Number.prototype.round2 = function (fractionDigits) {
    return accRound2(this, fractionDigits);
};
function gNum(sNumstr, fractionDigits) {
    if (fractionDigits != null) {
        return accRound2(parseFloat(sNumstr && sNumstr != 'undefined' && sNumstr != '' ? sNumstr : '0'), fractionDigits);
    } else {
        return parseFloat(sNumstr && sNumstr != 'undefined' && sNumstr != '' ? sNumstr : '0');
    }
};